'apiKey.id is required' error thrown when using express-stormpath with node.js - stormpath

I am using express-stormpath with node.js to set up a backend server. This is a snippet of my server.js code where I get an error thrown -
app.use(stormpath.init(app, {
apiKeyFile: './config/.stormpath/apikey.properties',
application: '<API_HREF>',
secretKey: security.stormpath_secret_key
}));
This is the error -
$ node server.js
../webservices/node_modules/express-
stormpath/node_modules/stormpath/lib/authc/RequestAuthenticator.js:8
throw new Error('apiKey.id is required.');
How do I fix this?

I'm assuming you're using the latest version of the express-stormpath library, which is why you're probably having issues. As of the 2.0.0 release, the library uses new configuration options.
Here's an example of the same thing using the new options:
app.use(stormpath.init(app, {
client: {
apiKey: {
file: './config/.stormpath/apikey.properties'
}
},
application: {
href: '<API_HREF>',
}
}));
NOTE: No secretKey is required, as this is generated automatically from your Stormpath API key secret =)
We've made many new changes in the latest library releases that enable all sorts of new, cool stuff! <3

Related

Reference Error {{variable}} is not defined at global in Rest Client in Visual Studio Code

I try to use Rest Client VS Code Extension from Huachao Mao. I created a new profile in my workspace settings
vs-code-workspace.code-workspace
{
"settings": {
"git.ignoreLimitWarning": true,
"rest-client.enableTelemetry": false,
"rest-client.environmentVariables": {
"xyz": {
"host": "http://localhost:8080/",
}
}
}
}
and I'm trying to send the following request
request.http
GET {{restBasePath}}/api/employee
but I'm getting
ReferenceError: host is not defined at global.<anonymous> (c:\Users\dev\request.http:3:20)
at N$ (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:191:43412)
at zCe (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:191:43961)
at c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:191:47073
at Jh (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:190:30551)
at Object.V3t [as action] (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:191:47038)
at I2e.<anonymous> (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extension.js:1:5703)
at Generator.next (<anonymous>)
at s (c:\Users\user\.vscode\extensions\anweber.vscode-httpyac-5.8.3\dist\extensi...
after I switched environment to xyz and tried to send the request. How to get rid of the error?
You mixed vscode-rest-client with vscode-httpyac. httpyac is an alternative to vscode-rest-client developed by me (see httpyac.github.io). To configure my extension use setting httpyac.environmentVariables. To use vscode-rest-client use codelens Send Request. I would be happy for you to try httpyac, but I would recommend using only one of the two extensions and disabling the other.

"Error: Unknown dialect undefined" when deploying Strapi 4.0 app to Heroku

I created a Strapi app using the latest version, the new 4.0 and I wanted to deploy it to Heroku. I did follow the Strapi documentation in order to do so, like explained in this page. Now I'm getting an error that I don't understand, I guess it has something to do with postgres. This is the error
2021-12-18T15:26:26.658380+00:00 app[web.1]: [2021-12-18 15:26:26.656] debug: ⛔️ Server wasn't able to start properly.
2021-12-18T15:26:26.659122+00:00 app[web.1]: [2021-12-18 15:26:26.658] error: Unknow dialect undefined
2021-12-18T15:26:26.659123+00:00 app[web.1]: Error: Unknow dialect undefined
2021-12-18T15:26:26.659123+00:00 app[web.1]: at getDialectClass (/app/node_modules/#strapi/database/lib/dialects/index.js:12:13)
2021-12-18T15:26:26.659123+00:00 app[web.1]: at getDialect (/app/node_modules/#strapi/database/lib/dialects/index.js:19:23)
2021-12-18T15:26:26.659124+00:00 app[web.1]: at new Database (/app/node_modules/#strapi/database/lib/index.js:38:20)
2021-12-18T15:26:26.659124+00:00 app[web.1]: at Function.Database.init (/app/node_modules/#strapi/database/lib/index.js:84:33)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at Strapi.bootstrap (/app/node_modules/#strapi/strapi/lib/Strapi.js:347:30)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at Strapi.load (/app/node_modules/#strapi/strapi/lib/Strapi.js:410:16)
2021-12-18T15:26:26.659125+00:00 app[web.1]: at async Strapi.start (/app/node_modules/#strapi/strapi/lib/Strapi.js:161:9)
Apart from doing what is explained in the docs I linked, I just added a few collections using the UI in development mode. How can I fix this error and deploy to Heroku this new 4.0 version of Strapi?
I had a similar issue when I was connecting pg locally and then realised my connection config was incorrect. When I replaced it with v4 template it worked.
path: config/database.js
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "bank"),
username: env("DATABASE_USERNAME", "postgres"),
password: env("DATABASE_PASSWORD", "0000"),
schema: env("DATABASE_SCHEMA", "public"),
},
}
});
And for Heorku as the article suggested:
path: config/env/production/database.js:
const parse = require('pg-connection-string').parse;
const config = parse(process.env.DATABASE_URL);
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false
},
},
debug: false,
},
});
PS: make sure you add pg-connection-string to your dependencies before pushing to heroku
getDialectClass - from the error log
const getDialectClass = client => {
switch (client) {
case 'postgres':
return require('./postgresql');
case 'mysql':
return require('./mysql');
case 'sqlite':
return require('./sqlite');
default:
throw new Error(`Unknow dialect ${client}`);
}
};
where the client is - db.config.connection
So if you have been following previous solutions - which talked about a connections object etc ( like this )
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'postgres',
host: config.host,
port: config.port,
database: config.database,
username: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
options: {
ssl: true,
},
},
},
});
db.config.connection would return undefined. & so it would fail
Configuring the DB with - https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/databases.html#configuration-structure
Works fine
If you are using typescript in Strapi, we may encounter this issue too as there is a issue affecting Strapi typescript capabilities.
I can resolve the problem when I downgraded Strapi to 4.3.2 from 4.3.8
You can check this method using heroku/cli from strapi docs here, but it's the same thing, i'm using version 4.0.2, this methods works on older versions V3, i think the docs needs update, most of it is deprecated, for example "fetching only data (example: posts/project etc..) related to the authenticated user who created it", most of resources related to this topic in docs and forum are deprecated solutions that don't work in V4.
For the deployment, i have the same issue, i tried a lot of solutions but it didn't work for me to, but i managed to get the server running like this:
but i got this problem when i visit the "/admin" page:
Strapi is really interesting, let's hope they update the docs soon and someone respond with a solution here.
I fixed this issue by using database url directly. Not sure why the old way does not work in Strapi v4.
module.exports = ({ env }) => ({
defaultConnection: "default",
connection: {
client: "postgres",
connection: {
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
},
}
});
In case someone meets the same problem as me.
In my situation, I am using vim in windows as my text editor. After editing the "config/database.js" file. It left a "database.js~" file in that directory. Then, this filename causes the same problems: "Error: Unknown dialect undefined".
I guess it's a bug in strapi. After removing that file, everything works!
So, the solutions for me. I add this line to my vim config file:
set backupdir=~/.vimbackup
Then create a directory named '.vimbackup' in "C:/User/[me]/" .
Strapi has once again changed the database configuration structure and even their deployment docs use the old and incorrect example.
Here is the most up to date example: Strapi Database Configuration
In strapi v4, you need to use like:
module.exports = ({ env }) => ({
connection: {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "localhost"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "db-name"),
user: env("DATABASE_USERNAME", "postgres"),
password: env("DATABASE_PASSWORD", "password"),
schema: env("DATABASE_SCHEMA", "public"),
},
}
});
it's look like there is a problem in the new strapi version , when i try to create project with typescript support i faced same error , i don't know if you are using typescript in your project but these two solutions solved my problem;
solution (1) :- create compile config ts files with tsc $ tsc .\config\database.ts .\config\server.ts ./ .\config\admin.ts
solution (2) :- downgrade your strapi to 4.3.2 version in the package.json file.
solution (3) :- don't use #latest when creating strapi app instate use 4.3.2 npx create-strapi-app#4.3.2 test-strapi-verion-with-ts --ts
you can use one of theme

Lambda Layers not installing with Serverless

Currently getting the following error with MongoDB:
no saslprep library specified. Passwords will not be sanitized
We are using Webpack so simply installing the module doesn't work (Webpack just ignores it). I found this thread which talks about how to exclude it from Webpack compilations, but then I have to manually load it into every Lambda function which led me to Lambda Layers.
Following the Serverless guide on using Lambda layers allowed me to get my layer published to AWS and included in all of my functions, but for some reason, it doesn't install the modules. If I download the layer using the AWS GUI, I get a folder with just the package.json and package-lock.json files.
My file structure is:
my-project
|_ layers
|_ saslprep
|_ package.json
and my serverless.yml is:
layers:
saslprep:
path: layers/saslprep
compatibleRuntimes:
- nodejs14.x
This is not my preferred solution as I'd like to use 256, but the way I got around this error/warning was by changing the authMechanism from SCRAM-SHA-256 to SCRAM-SHA-1 in the connection string. The serverless-bundle most likely needs to add this dependency into their package to enable support for Mongo 4.0 SHA256 (my best guess!).
You can specify this authentication mechanism by setting the authMechanism parameter to the value SCRAM-SHA-1 in the connection string as shown in the following sample code.
const { MongoClient } = require("mongodb");
// Replace the following with values for your environment.
const username = encodeURIComponent("<username>");
const password = encodeURIComponent("<password>");
const clusterUrl = "<MongoDB cluster url>";
const authMechanism = "SCRAM-SHA-1";
// Replace the following with your MongoDB deployment's connection string.
const uri =
`mongodb+srv://${username}:${password}#${clusterUrl}/?authMechanism=${authMechanism}`;
// Create a new MongoClient
const client = new MongoClient(uri);
// Function to connect to the server
async function run() {
try {
// Connect the client to the server
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

Using SocketIo Manager with a default URL

My goal is to add a token in the socketio reconnection from the client (works fine on the first connection, but the query is null on the reconnection, if the server restarted while the client stayed on).
The documentation indicates I need to use the Manager to customize the reconnection behavior (and add a query parameter).
However, I'm getting trouble finding how to use this Manager: I can't find a way to connect to the server.
What I was using without Manager (works fine):
this.socket = io({
query: {
token: 'abc',
}
});
Version with the Manager:
const manager = new Manager(window.location, {
hostname: "localhost",
path: "/socket.io",
port: "8080",
query: {
auth: "123"
}
});
So I tried many approaches (nothing, '', 'http://localhost:8080', 'http://localhost:8080/socket.io', adding those lines to the options:
hostname: "localhost",
path: "/socket.io",
port: "8080" in the options,
But I couldn't connect.
The documentation indicates the default URL is:
url (String) (defaults to window.location)
For some reasons, using window.location as URL refreshes the page infinitely, no matter if I enter it as URL in the io() creator or in the new Manager.
I am using socket.io-client 3.0.3.
Could someone explain me what I'm doing wrong ?
Thanks
Updating to 3.0.4 solved the initial problem, which was to be able to send the token in the initial query.
I also found this code in the doc, which solves the problem:
this.socket.on('reconnect_attempt', () => {
socket.io.opts.query = {
token: 'fgh'
}
});
However, it doesn't solve the problem of the Manager that just doesn't work. I feel like it should be removed from the doc. I illustrated the problem in this repo:
https://github.com/Yvanovitch/socket.io/blob/master/examples/chat/public/main.js

GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types

I am trying to follow the documentation on the Nexus-Schema (nexusjs) website for adding scalar types to my GraphQL application.
I have tried adding many of the different implementations to my src/types/Types.ts file using the samples provided in the documentation and the interactive examples. My attempts include:
Without a 3rd party libraries:
const DateScalar = scalarType({
name: 'Date',
asNexusMethod: 'date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value)
},
serialize(value) {
return value.getTime()
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(ast.value)
}
return null
},
})
With graphql-iso-date 3rd party library:
import { GraphQLDate } from 'graphql-iso-date'
export const DateTime = GraphQLDate
With graphql-scalars 3rd party library (as shown in the ghost example):
export const GQLDate = decorateType(GraphQLDate, {
rootTyping: 'Date',
asNexusMethod: 'date',
})
I am using this new scalar type in an object definition like the following:
const SomeObject = objectType({
name: 'SomeObject',
definition(t) {
t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`
},
})
In all cases, these types are exported from the types file and imported into the makeSchema's types property.
import * as types from './types/Types'
console.log("Found types", types)
export const apollo = new ApolloServer({
schema: makeSchema({
types,
...
context:()=>(
...
})
})
The console.log statement above does show that consts declared in the types file are in scope:
Found types {
GQLDate: Date,
...
}
If I run the app in development mode, everything boots up and runs fine.
ts-node-dev --transpile-only ./src/app.ts
However, I encounter errors whenever I try to compile the app to deploy to a server
ts-node ./src/app.ts && tsc
Note: This error occurs occurs running just ts-node ./src/app.ts before it gets to tsc
The errors that shown during the build process are the following:
/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock<"SomeObject">'.
11 t.date('createdAt')
Does anyone have any ideas on either:
a) How can I work around this error? While long-term solutions are ideal, temporary solutions would also be appreciated.
b) Any steps I could follow to debug this error? Or ideas on how get additional information to assist with debugging?
Any assistance would be very much welcomed. Thanks!
The issue seems to be resolved when --transpile-only flag is added to the nexus:reflect command.
This means the reflection command gets updated to:
ts-node --transpile-only ./src/app.ts
and the build comand gets updated to:
env-cmd -f ./config/.env ts-node --transpile-only ./src/app.ts --nexusTypegen && tsc
A github issue has also been created which can be reviewed here: https://github.com/graphql-nexus/schema/issues/690

Resources