Receiving 401 Unauthorized error in Sendgrid with Strapi - javascript

I'm trying to add a "forgot password" link in my application, using the built-in API provided by Strapi. I've included the configuration for Sendgrid in config/plugins.js:
module.exports = ({ env }) => ({
email: {
provider: "sendgrid",
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: "myemail#gmail.com",
defaultReplyTo: "myemail#gmail.com",
},
},
});
Every answer I find about this error is about adding the API key in the environment variables, which I've already done (and re-done) several times. I also re-created my API key twice, in case it expired, but it's still the same. I don't understand, it was working perfectly well a couple days ago but now I'm stuck on this error. Any idea what could be the issue here?

Probably indeed the expression env('SENDGRID_API_KEY') is not resolving the correct api key. You can also directly put your api key in the json like this:
module.exports = ({ env }) => ({
email: {
provider: "sendgrid",
providerOptions: {
apiKey: 'SG.MY_SENDGRID_API_KEY',// <== not using the env function
},
settings: {
defaultFrom: "myemail#gmail.com",
defaultReplyTo: "myemail#gmail.com",
},
},
If this works, the plugin is working, and you can focus on why the env() function is not resolving the variable

Related

Cannot make Cypress and Pact work together

I already have working project with few passing Cypress tests.
Now I'm trying to add contract tests using Cypress + Pact
In developer console I can see that app is calling /api/v1/document-service, but I get:
Pact verification failed - expected interactions did not match actual.
Part of logs:
W, [2021-07-20T12:49:37.157389 #34805] WARN -- : Verifying - actual interactions do not match expected interactions.
Missing requests:
POST /api/v1/document-service
W, [2021-07-20T12:49:37.157489 #34805] WARN -- : Missing requests:
POST /api/v1/document-service
I'm using:
cypress: 7.5.0
#pact-foundation/pact: 9.16.0
Steps I've done:
Added cypress plugin (https://github.com/pactflow/example-consumer-cypress/blob/master/cypress/plugins/cypress-pact.js)
Added commands (https://github.com/pactflow/example-consumer-cypress/blob/master/cypress/support/commands.js)
Added config to cypress.json (https://github.com/pactflow/example-consumer-cypress/blob/master/cypress.json) - not sure what to put to baseUrl, if I don't want interactions with real server.
Added test:
let server;
describe('Simple', () => {
before(() => {
cy.mockServer({
consumer: 'example-cypress-consumer',
provider: 'pactflow-example-provider',
}).then(opts => {
cy.log(opts)
server = opts
})
});
beforeEach(() => {
cy.fakeLogin()
cy.addMockRoute({
server,
as: 'products',
state: 'products exist',
uponReceiving: 'a request to all products',
withRequest: {
method: 'POST',
path: '/api/v1/document-service',
},
willRespondWith: {
status: 200,
body: {
data: {
collections: [
{
id: '954',
name: 'paystubs',
},
{
id: '1607',
name: 'mystubs',
},
],
},
},
},
});
});
it('is ok?', () => {
cy.visit('/new/experiments/FirstProject/collections');
});
})
Tried both using deprecated cy.server()/cy.route() and new cy.intercept(), but still verification failures.
At Pactflow, we've spent about 6 months using Cypress and Pact together, using the Pact mock service to generate pacts from our Cypress tests as suggested in https://pactflow.io/blog/cypress-pact-front-end-testing-with-confidence/
We have this week decided to change our approach, for the following reasons.
Our Cypress tests are much slower than our unit tests (15+ minutes), so generating the pact, and then getting it verified takes a lot longer when we generate the pact from our Cypress tests vs our unit tests.
Our Cypress tests can fail for reasons that are not to do with Pact (eg. layout changes, issues with the memory consumption on the build nodes, UI library upgrades etc) and this stops the pact from being generated.
The Cypress intercept() and mock service don't play very nicely together. Any request that does not have an explicit intercept() for Cypress ends up at the mock service, and every time a new endpoint is used by the page, the request hits the mock service, which then fails the overall test, even if that endpoint was not required for that specific test.
When a Cypress test fails, there is very good debugging provided by the Cypress library. When it fails for reasons to do with Pact, it's currently hard to identify the cause, because that information is not displayed in the browser (this could potentially be improved, however, it won't mitigate the already listed issues).
Our new approach is to generate our Pacts from our unit tests (instead of our Cypress tests) and to share the fixtures between the unit and Cypress tests, using a function that strips of the Pact matchers. eg.
const SOME_INTERACTION = {
state: 'some state',
uponReceiving: "some request",
withRequest: {
method: "GET",
path: "/something"
},
willRespondWith: {
status: 200,
body: {
something: like("hello")
}
}
}
Unit test
describe('Something', () => {
let someProviderMockService
beforeAll(() => {
someProviderMockService = new Pact({
consumer: 'some-consumer',
provider: 'some-provider'
})
return someProviderMockService.setup()
})
afterAll(() => someProviderMockService.finalize())
afterEach(() => someProviderMockService.verify())
describe('loadSomething', () => {
beforeEach(() => {
return someProviderMockService.addInteraction(SOME_INTERACTION)
})
it('returns something', async () => {
const something = await loadSomething()
//expectations here
})
})
})
Function that turns the Pact interaction format into Cypress route format, and strips out the Pact matchers.
const Matchers = require('#pact-foundation/pact-web').Matchers
// TODO map the request body and query parameters too
const toCypressInteraction = (interaction) => {
return {
method: interaction.withRequest.method,
url: Matchers.extractPayload(interaction.withRequest.path),
status: interaction.willRespondWith.status,
headers: Matchers.extractPayload(interaction.willRespondWith.headers),
response: Matchers.extractPayload(interaction.willRespondWith.body)
}
}
In the Cypress test
cy.route(toCypressInteraction(SOME_INTERACTION))
This approach has the following benefits:
The pact is generated quickly.
The pact is generated reliably.
The Cypress tests are more reliable and easier to debug.
The requests used in the Cypress tests are verified to be correct.
There is less chance of "interaction bloat", where interactions are added merely to test UI features, rather than because they provide valuable coverage.
I hope this information is helpful for you. We now recommend this approach over direct use of the mock service in Cypress tests.

Cloud function deployment failure

I am trying to deploy my Cloud Function using Cloud Firestore as Trigger. The Cloud function simply listens to any new document creation on my firestore path and logs the new data to the console. However, the function deployment is failing and there is no clear error message. Could you please help me identify what could be the issue?
Cloud Function Code:
const functions = require('firebase-functions');
exports.createUser = functions.firestore
.document('test_restaurant/{id}/reviews/{id}')
.onCreate((snap, context) => {
console.log(snap.data());
});
Error Log:
2020-06-28 18:51:03.110 IST
Cloud Functions
UpdateFunction
asia-east2:function-test-2
abc#gmail.com
Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs
Expand all | Collapse all
{
insertId: "5u231ccch0"
logName: "projects/fs-22/logs/cloudaudit.googleapis.com%2Factivity"
operation: {
id: "operations/ZmlyZXN0b3JlLTI0OTcwNS9hc2lhLWVhc3QyL2Z1bmN0aW9uLXRlc3QtMi9xOVJCbHpESzdjSQ"
last: true
producer: "cloudfunctions.googleapis.com"
}
protoPayload: {
#type: "type.googleapis.com/google.cloud.audit.AuditLog"
authenticationInfo: {
principalEmail: "abc#gmail.com"
}
methodName: "google.cloud.functions.v1.CloudFunctionsService.UpdateFunction"
resourceName: "projects/fs-22/locations/asia-east2/functions/function-test-2"
serviceName: "cloudfunctions.googleapis.com"
status: {
code: 3
message: "Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs"
}
}
receiveTimestamp: "2020-06-28T13:21:03.364975479Z"
resource: {
labels: {
function_name: "function-test-2"
project_id: "fs-22"
region: "asia-east2"
}
type: "cloud_function"
}
severity: "ERROR"
timestamp: "2020-06-28T13:21:03.110Z"
}
The issue resolved. Basically the error was using the same wildcard twice in the document path. The reference causing the problem was {id}, I just changed one of those references. The new path is: .document('test_restaurant/{id}/reviews/{reviewsId}') and the deployment succeeded.
Check if you have some dependencies installed on your root folder. You should have all your modules installed inside the functions folder. Only firebase dependencies should be in your root folder. Try to do npm uninstall yourDependencie inside your root folder and then npm i yourDependencie inside root/functions folder.
If you are using lint, you need to make sure your code is passing eslint . command, other wise youl'll get that error deploying to firebase
{
"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{
"code":3,
"message":"Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging"
},
"authenticationInfo":{
"principalEmail":"your_email"
},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/your_project/locations/us-central1/functions/your_func"
}
For my case I fix it by dissabling prettier on index, also, if you have more files you have to disable it for each one.
/* eslint-disable prettier/prettier */

Is aws-amplify with auth broken?

I am trying to build a react app which will use the aws hosted ui for authentication. I am trying to use aws-amplify to achieve this, and so far I am having no such luck.
Here the docs state that the auth config should look like this.
const oauth = {
domain : 'your-domain-prefix.auth.us-east-1.amazoncognito.com',
scope : ['phone', 'email', 'profile', 'openid','aws.cognito.signin.user.admin'],
redirectSignIn : 'http://www.example.com/signin/',
redirectSignOut : 'http://www.example.com/signout/',
responseType: 'code',
}
But when I use this config setup I get the following error.
The parameters: App client Id, App web domain, the redirect URL when
you are signed in and the redirect URL when you are signed out are
required.
As you can see, those params are clearly supplied. So I clicked on the source map file linked in my console with the error message, and saw this.
if (data == null || !ClientId || !AppWebDomain || !RedirectUriSignIn || !RedirectUriSignOut) {
throw new Error(this.getCognitoConstants().PARAMETERERROR);
}
Which makes it seem more like the config should look a little something like this.
const auth = {
AppWebDomain: "aaaaa",
TokenScopesArray: ["phone", "email", "profile", "openid", "aws.cognito.signin.user.admin"],
RedirectUriSignIn: "http://localhost:3000",
RedirectUriSignOut: "http://localhost:3000",
responseType: "token",
ClientId: "aaa",
UserPoolId: "aaa",
};
But when doing this, and trying to send the user to the hosted ui as the docs say here I get this error.
Uncaught TypeError: Cannot read property 'domain' of undefined
Once again I looked at the source and found this.
var domain = config.domain,
Which makes it seem like its expecting the config which does not work.
At this point I am really lost and can use any help at all.
Going through the Auth.ts code, it appears that you have to include the userPoolId and userPoolWebClientId fields, in addition to oauth. Here's how I got it to work:
const oauth = {
domain: 'XXXXXX.auth.us-west-2.amazoncognito.com',
scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
redirectSignIn: 'http://localhost:3000/',
redirectSignOut: 'http://localhost:3000/',
responseType: 'code'
};
Auth.configure({
oauth: oauth,
region: 'us-west-2',
userPoolId: 'us-west-2_XXXXXXXXX',
userPoolWebClientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
});

Firebase Cloud Functions - onCall not working

I'm testing a very simple implementation as described on FB docs (https://firebase.google.com/docs/functions/callable), and it's not working.
Here's my Firebase Function, deployed to cloud:
exports.getRecSkills = functions.https.onCall((data, context) => {
return {text: data.text};
});
...and my client call (after initializing FB):
var getRecSkills = firebase.functions().httpsCallable('getRecSkills');
getRecSkills({text: '123'}).then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
I get a CORS header related issue but in the docs, it doesn't mention the need for CORS... am I missing something?
Some notes:
I've been able to execute other Firebase Functions (i.e. HTTPS,
Database) so I don't think it's me setting up Firebase wrong.
Updated to latest Firebase, so don't think that's an issue either.
Gives me an "internal" error, which the API docs aren't helpful, other than "something is seriously wrong".
I can't seem to get the function to work (it keeps giving me
400-errors) when testing locally via the shell, even though I got it
to work with any other database and https functions
Been struggling with this for quite some time... Please help!
To get rid of your CORS error, make sure your firebase.json has the following headers:
"hosting": [
{
"headers": [
{
"source": "**",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
}
]
If you're running on Firebase Emulator on local device, make sure you have the following after initializing your Firebase Functions, otherwise your local device will still be calling the remote the Firebase Function and you'll hit the CORS error again:
if (window.location.hostname === "localhost") {
console.log("localhost detected!");
firebase.functions().useFunctionsEmulator('http://localhost:5001');
};
I had the same problem just recently but solved it after including my "projectId" in my config object. Below is a code snippet of the Firebase config object for Javascript. Make sure all fields have been filled in your config object and it should solve your undefined issue.
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
If you have CORS issues and you are using express in order to expose the API functions you have to allow cors:
import * as cors from 'cors';
import * as express from 'express';
const corsHandler = cors({origin: true});
const app = express();
app.use(corsHandler);
app.post('/createUser', async (request, response) => {
await createUser(request, response);
});
exports.api = functions.https.onRequest(app);

Meteor-Up (mup) error after "mup init"

I am trying to use mup to deploy a meteor app to my DigitalOcean droplet.
What I have done so far
Followed instructions on "Meteor-Up" website http://meteor-up.com/getting-started.html.
Installed mup via "npm install --global mup"
Created ".deploy" folder in my app directory. Ran "mup init".
Configured file "mup.js" file for my app, ran "mup setup".
Here is where I ran into an error. Upon running "mup setup", I am hit with the following error. [
What I tried:
I suspected that there could have been an issue with my syntax when configuring the mup.js file. After double-checking and not finding any error, I decided to re-install mup, and try running "mup setup" without modifying the "mup.js" file. However, I still receive the same error message.
Furthermore, after running "mup init", I can no longer run "mup" either, as I receive the same error as seen above. I suspect therefore that the issue is with the mup.js file. I have attached the generic version provided by meteor-up below (which still causes the error seen above).
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
app: {
// TODO: change app name and path
name: 'app',
path: '../app',
servers: {
one: {},
},
buildOptions: {
serverOnly: true,
},
env: {
// TODO: Change to your app's url
// If you are using ssl, it needs to start with https://
ROOT_URL: 'http://app.com',
MONGO_URL: 'mongodb://localhost/meteor',
},
// ssl: { // (optional)
// // Enables let's encrypt (optional)
// autogenerate: {
// email: 'email.address#domain.com',
// // comma separated list of domains
// domains: 'website.com,www.website.com'
// }
// },
docker: {
// change to 'abernix/meteord:base' if your app is using Meteor 1.4 - 1.5
image: 'abernix/meteord:node-8.4.0-base',
},
// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
mongo: {
version: '3.4.1',
servers: {
one: {}
}
}
};
Any help would be greatly appreciated!
Thank you
The error dialog you posted shows a syntax error at line 10, character 5.
If you take a look:
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
^^^ This character
},
It's a closing brace which JS was not expecting. So why was it unexpected, lets move back to the last valid syntax:
module.exports = {
servers: {
one: {
// TODO: set host address, username, and authentication method
host: '1.2.3.4',
username: 'root',
^^^ This character
// pem: './path/to/pem'
// password: 'server-password'
// or neither for authenticate from ssh-agent
}
},
Well, looks like a comma which isn't followed by another key-value pair. Also known as a syntax error.
Take the comma out and things should be fine again!
I faced this same issue today. The problem is that Windows is trying to execute the mup.js file as a JScript script.
Here is the solution from the Meteor Up Common Problems page:
Mup silently fails, mup.js file opens instead, or you get a Windows script error
If you are using Windows, make sure you run commands with mup.cmd instead of mup , or use PowerShell.
That is, instead of mup setup, run mup.cmd setup.

Categories