Why Nuxt making multiple request for the "user" endpoint? - javascript

There is an Express server and a Nuxt client. Nuxt version is 2.15.7.
Entire auth configuration:
// nuxt.config.js
auth: {
plugins: [
{
src: '~/plugins/axios',
ssr: true
},
{
src: '~/plugins/auth'
}
],
cookie: {
prefix: 'auth.',
options: {
path: '/',
secure: process.env.NODE_ENV === 'production' ? true : false
}
},
localStorage: {
prefix: 'auth.'
},
vuex: {
namespace: 'auth'
},
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'accessToken',
maxAge: 900,
global: true,
name: 'Authorization',
type: 'Bearer'
},
refreshToken: {
property: 'refreshToken',
data: 'refreshToken',
maxAge: 5184000
},
user: {
property: 'user',
autoFetch: false
},
endpoints: {
login: {
url: '/user/sign_in',
method: 'post'
},
logout: {
url: '/user/sign_out',
method: 'delete'
},
refresh: {
url: '/user/refresh',
method: 'get'
},
user: {
url: '/user/profile',
method: 'get'
}
}
}
},
redirect: {
login: '/auth/sign_in',
logout: '/',
callback: '/auth/sign_in',
home: '/'
}
}
When I refresh the page in the browser, I see this in the browser log:
This message comes from here:
// plugins/axios.ts
import { AxiosRequestConfig } from 'axios'
export default function ({ $axios, }: any) {
$axios.onRequest((config: AxiosRequestConfig) => {
console.log('Making request to ' + config.url)
})
}
There are also two requests in the server logs. But in the first request I can get, for example, cookies, and in the second one comes this:
// console.log(req.cookies)
[Object: null prototype] {}
Can you please tell me why there are two requests?

The problem was caused by the back end returning this after sign in:
{
"is": 1
}
And should return this:
{
"user": {
"is": 1
}
}
😬
After I added the "user" object, nuxt auth accepted the information and started working correctly.

Related

What is [Symbol(kHeaders)] and how do I parse it as headers

I am having trouble parsing the header retrieved from graphql's context, what I would like to do is to basically forward the headers from the request into the response
My gateway:
GraphQLModule.forRootAsync<ApolloGatewayDriverConfig>({
driver: ApolloGatewayDriver,
inject: [ConfigService],
useFactory: async(configService: ConfigService) => ({
server: {
introspection: true,
playground: true,
cache: 'bounded'
},
gateway: {
buildService: (url) => new CustomDataSource(url),
supergraphSdl: ...
}
})
})
My CustomDataSource which should forward headers:
export class CustomDataSource extends RemoteGraphQLDataSource {
constructor(config: any) {
super(config);
this.fetcher = fetcher.defaults({
maxSockets: Infinity,
strictSSL: false,
retry: false,
})
}
willSendRequest({context, request }) {
console.log('context', context.req); // <---- here
request.http?.headers.set('authorization', context.req.authorization);
}
}
My issue now is that the context.req.headers do not exist when it should and logging it out gives me headers in a different name as kHeaders instead which I am unsure of how to parse this.
context.req:
{
...,
...,
[Symbol(kHeaders)]: {
authorization: 'abcdefg'
}
}
I tried something like context.req['Symbol(kHeaders)'] which returns me cannot read properties, would like to know why is my headers returned this way and how do I parse this

cypress.origin throws error: (uncaught exception)Error: on only accepts instances of Function

I am using Cypress with Cucumber.
I am trying to test cross origin login but the origin method keeps on throwing error:
Code:
Given(/^the user login to the Test Page$/, function () {
cy.visit("https://example-originalURL");
cy.get("button").contains("Login").click();
const credentials = {
username: "hello",
password: "user",
};
cy.origin("https://example-newURL", { args: credentials }, ({ username, password }) => {
cy.get("#email", { timeout: 20000 }).type(username);
cy.get("#password").type(password, { log: false });
cy.get("button").contains("Login").click();
});
});
Cypress.config.js
module.exports = defineConfig({
projectId: "t7unhv",
e2e: {
setupNodeEvents(on, config) {
on("file:preprocessor", cucumber());
on('task', {
log(message) {
console.log(message +'\n\n');
return null;
},
});
},
specPattern: "./cypress/e2e/features/*.feature",
chromeWebSecurity: false,
experimentalSessionAndOrigin: true,
defaultCommandTimeout: 15000,
env: {
devCentralUrl: "https://***.dev.***.com.au/login",
testCentralUrl:
"https://***.test.***.com.au/login",
test***: "http://***.test.***.com.au",
dev***: "http://***.dev.***.com.au",
uat***: "https://***.uat.***.com.au",
dataSource: "",
environs: "test",
},
retries: {
runMode: 0,
},
pageLoadTimeout: 15000,
reporter: "mochawesome",
reporterOptions: {
reporterEnabled: "mochawesome",
mochawesomeReporterOptions: {
reportDir: "cypress/reports/mocha",
quite: true,
charts: true,
overwrite: false,
html: false,
json: true,
},
},
},
});
Error:
The following error originated from your test code, not from Cypress.
> on only accepts instances of Function
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
I have tried multiple syntax changes like not passing the credentials as optional argument to cy.origin.
If someone can provide a quick help, that will be great.
If the problem is in the test code, it is likely to be that newURL is undefined. The error message suggests the problem is in the app, but that might be a red herring.
Try just adding a fixed string for the cy.origin() key,
cy.origin('login', { args: credentials }, ({ username, password }) => {
...
})

how to add authentication in nuxt.js content docs theme

I have created a NUXT.JS content static site served with .md files. Now i want to add authentication to it. I want to redirect a user form my main site which is built in VUE.JS
User have to login to my main site and then clicking on a link -> redirect the user to nuxt site
Here are my nuxt configs:
import theme from '#nuxt/content-theme-docs'
export default theme({
docs: {
primaryColor: '#E24F55'
},
content: {
liveEdit: false
},
buildModules: [
'#nuxtjs/color-mode'
],
colorMode: {
preference: '', // default value of $colorMode.preference
fallback: 'light', // fallback value if not system preference found
hid: 'nuxt-color-mode-script',
globalName: '__NUXT_COLOR_MODE__',
componentName: 'ColorScheme',
classPrefix: '',
classSuffix: '-mode',
storageKey: 'nuxt-color-mode'
},
})
-------->>>>>>>>
In middleware>stats.js
export default function ({ route, redirect }) {
console.log('route', route)
// api call to check further
}
nuxt.config.js
import theme from '#nuxt/content-theme-docs'
export default theme({
docs: {
primaryColor: '#E24F55'
},
modules: ['#nuxtjs/axios'],
router: {
middleware: 'stats'
}
})
Here is a local/jwt example of how to use nuxt-auth in #nuxt/docs theme.
The file structure:
├───components
│ └───global
auth.vue
├───content
│ └───en
playground.md
├───node_modules
├───nuxt.config
├───package.json
├───static
// nuxt.config.js
import theme from "#nuxt/content-theme-docs";
export default theme({
docs: {
primaryColor: "#E24F55",
},
content: {
liveEdit: false,
},
buildModules: ["#nuxtjs/color-mode"],
colorMode: {
preference: "", // default value of $colorMode.preference
fallback: "light", // fallback value if not system preference found
hid: "nuxt-color-mode-script",
globalName: "__NUXT_COLOR_MODE__",
componentName: "ColorScheme",
classPrefix: "",
classSuffix: "-mode",
storageKey: "nuxt-color-mode",
},
// ---->
auth: {
strategies: {
local: {
token: {
property: "token",
// required: true,
// type: 'Bearer'
},
user: {
property: "user",
// autoFetch: true
},
endpoints: {
login: { url: "/api/auth/login", method: "post" },
logout: { url: "/api/auth/logout", method: "post" },
user: { url: "/api/auth/user", method: "get" },
},
},
},
},
// <----
});
// components/global/auth.vue
<template>
<div>
<form #submit.prevent="userLogin">
<div>
<label>Username</label>
<input type="text" v-model="login.username" />
</div>
<div>
<label>Password</label>
<input type="text" v-model="login.password" />
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
login: {
username: '',
password: ''
}
}
},
methods: {
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
}
}
}
</script>
and in your *.md file use the auth component:
---
title: Playground
description: ''
position: 1
category: Playground
---
<auth></auth>
This example is quite simple. It is only meant to show how to use nuxt auth in the nuxt docs theme.
oh ok, you're right, he can't register the middleware.
But you can create a plugin with beforeEach.
// plugins/guard.js
export default ({ app }) => {
app.router.beforeEach((to,from, next) => {
console.log(to, from)
next()
})
}
// nuxt.config.js
// ...
plugins: [__dirname + '/plugins/guard.js'],
// ...
I've spent some time redacting how to do it. Unfortunately I could not make proper edited and annotated screenshots of the Auth0 (too cumbersome with my current setup to make something clean) but here is my github repo with all the explanations on how to make this work.
https://github.com/kissu/so-nuxt-docs-theme-auth-auth0

Nuxt.js auth module does not redirect logged in user

Authenticated user can still access the /login page. If I follow a link to /login page, I am redirected to a different page, which works fine. But if I enter /login into URL manually, I am still being taken to /login page, even though I am already logged in. What I am trying to achieve is, when the user is logged in, they should be redirected to /retailer/account page before any components are shown on the page (if they enter /login page manually).
I was trying using beforeMount() function, beforeCreate() function, following the documentation for auth: 'guest' middleware, however it does not seem to have any effect and loggedIn always returns false before the page is fully rendered.
My setup:
nuxt.config.js :
export default {
mode: 'universal',
target: 'static',
auth: {
cookie: {
prefix: 'auth_'
},
// Options
redirect: {
login: '/login',
logout: '/login',
callback: false,
home: '/retailer/account'
},
strategies: {
local: {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token',
credentials: true
},
logout: {
url: '/auth/logout',
method: 'post'
},
user: {
url: '/auth/me',
method: 'post',
propertyName: '',
credentials: false
}
},
token: {
required: true,
type: 'Bearer',
global: true
},
autoFetchUser: true
}
},
preserveState: true,
watchLoggedIn: true
},
router: {
middleware: [
'auth'
]
}
}
layouts/default.vue :
export default {
auth: false
}
pages/retailer/account.vue :
export default {
middleware: 'auth'
}
pages/login.vue :
export default {
middleware: 'authenticated',
auth: 'guest'
}
Tried all kinds of middleware examples I could find and made some simple redirection code, but, as mentioned before, app.$auth.loggedIn always returns false from server-side, so I never get redirected.
middleware/authenticated.js
export default function ({ app, redirect }) {
if (app.$auth.loggedIn) {
return redirect(app.localePath({ name: 'index' }))
}
}
Later, when Vue hydrates the app, loggedIn is, of course, true.
Any ideas what I am doing wrong? Any guidance would be a huge help!
Nuxt auth module has a middleware auth can redirect unauthenticated user to login page, and redirect authenticated to home.
I see than the auth middleware is configured correctly in you nuxt.config.js.
The problem is that auth middleware only works on server side for SSR. but you configured to generate static website.
You can remove line target: 'static', from nuxt.config.js.
Or fllow this issue to find some help for static site auth:
https://github.com/nuxt/nuxt.js/issues/3023

hapi-swagger disables my routes

Below is the glue manifest I use to fire up the server:
var Config = require('../config.json');
var internals = {
manifest: {
connections: [
{
host : Config.host || process.env.IP,
port : Config.apiPort || process.env.PORT,
labels : ['api']
}],
plugins: {
'./decorate': [{ 'select': ['api']}],
'hapi-auth-jwt': [{ 'select': ['api']}],
'./authentication': [{ 'select': ['api']}],
'./controllers': [{ 'select': ['api']}],
'./models': [{ 'select': ['api']}],
'./api': [{ 'select': ['api']}],
good: {
opsInterval: 5000,
reporters: [
{ 'reporter': 'good-console', 'events': { 'log': '*' } }
]
}
}
}
};
if (!process.env.PRODUCTION) {
internals.manifest.plugins['blipp'] = [{}];
internals.manifest.plugins['good'].reporters[0].events['ops'] = '*';
}
module.exports = internals.manifest;
As soon as I add 'hapi-swagger' to the list of plugins the server stops responding to the routes defined in the ./api file. None of the routes work. Is the the right way to add hapi-swagger to the glue manifest or am I doing something absurd?
EDIT: Below is the api.js
exports.register = function (plugin, options, next) {
plugin.dependency('controllers');
plugin.dependency('models');
var Controllers = plugin.plugins.controllers.handlers;
var Models = plugin.plugins.models.models;
plugin.bind({
models: Models
});
plugin.route([
{ method: 'GET', path: '/token', config: Controllers.Membership.token },
{ method: 'GET', path: '/', config: Controllers.Home.status },
{ method: 'GET', path: '/nodes', config: Controllers.Node.search },
{ method: 'GET', path: '/services', config: Controllers.Node.services },
{ method: 'GET', path: '/createnodetree', config: Controllers.Loader.createNodeTree }
]);
next();
};
exports.register.attributes = {
name: 'api',
version: require('../package.json').version
};
This happens if you try to use hapi-swagger without either including the documentation view dependencies or properly disabling documentation support. From the docs:
If you want to view the documentation from your API you will also need to install the inert and vision plugs-ins which support templates and static content serving. If you wish just to used swagger.json without the documentation for example with swagger-codegen simply set options.enableDocumentation to false.
You didn't show how you are adding the hapi-swagger plugin but you simply need to add 'enableDocumentation': false to options wherever you define that. You can find examples at the link above.

Categories

Resources