CouchDB throws '404 missing' error when inserting a user using nano - node.js

It seems CouchDB will randomly throw an error when trying to insert a user.
Here is the full response from CouchDB:
{ [Error: missing]
name: 'Error',
scope: 'couch',
status_code: 404,
'status-code': 404,
request:
{ method: 'POST',
headers:
{ 'content-type': 'application/json',
accept: 'application/json',
'X-CouchDB-WWW-Authenticate': 'Cookie',
cookie: [Object] },
uri: 'http://127.0.0.1:5984/_users',
body: '{"_id":"org.couchdb.user:fake_user","name":"fake_user","realname":"fake user","institution":"366a8e5ba861bdd9cad5cd318a002ee4","email":"fake_user#gmail.com","phone":"123-456-7890","type":"user","roles":[],"password":"123456","level":"user","unconfirmed":"true"}',
jar: false },
headers:
{ date: 'Tue, 21 Jan 2014 20:32:23 GMT',
'content-type': 'application/json',
'cache-control': 'must-revalidate',
'status-code': 404,
uri: 'http://127.0.0.1:5984/_users' },
errid: 'non_200',
error: 'not_found',
reason: 'missing',
description: 'missing',
stacktrace:
[ 'Error: missing',
' at Request._callback (/apps/arcapp/node_modules/nano/nano.js:304:39)',
' at Request.self.callback (/apps/arcapp/node_modules/nano/node_modules/request/request.js:129:22)',
' at Request.EventEmitter.emit (events.js:98:17)',
' at Request.<anonymous> (/apps/arcapp/node_modules/nano/node_modules/request/request.js:873:14)',
' at Request.EventEmitter.emit (events.js:117:20)',
' at IncomingMessage.<anonymous> (/apps/arcapp/node_modules/nano/node_modules/request/request.js:824:12)',
' at IncomingMessage.EventEmitter.emit (events.js:117:20)',
' at _stream_readable.js:872:14',
' at process._tickCallback (node.js:415:13)' ] }
This is obviously not very insightful. All I get is error: not_found, reason: missing, which doesn't tell me much. It only happens sometimes and I can't really tell what's triggering it. Any insight into this is much appreciated.
Here is the relevant code. I'm using nano, but it's just a basic post request to CouchDB.
var user = {
"_id": "org.couchdb.user:" + username,
"name": username,
"realname": first + " " + last,
"institution": institution,
"email": email,
"phone": phone,
"type": "user",
"roles": [],
"password": password,
"level": "user",
"unconfirmed": "true",
"verificationCode": verificationCode
};
nano.request({
db: '_users',
method: 'POST',
body: user
}, function(err, body) {
if(err) {
console.log("ERROR INSERTING USER");
console.log(err);
res.send(err.status_code + " " + err.reason, err.status_code);
return;
}
...

The problem here was that the cookie I was using to validate a user was not being properly unset after logout. So if you logged out and immediately tried to register, the database would authenticate the request as the logged in user. Since only db administrators are allowed access to the _users db, CouchDB would throw a '404 missing' error.
I was setting nano.config.cookie on login, so when I unset it on logout, it worked!

This error rings a bell but unfortunately I'm not 100% how/if I fixed it.
One thing I did notice you are including "roles:[]" I dont think this is allowed unless your post as an admin.
I haven't enough rep to comment but can you send the code that's making the request ?

Related

Problems with getting Apple Pay payment session

A year ago we implemented ApplePay on the web in our project and everything worked just fine. But now it's unstable and payment can be successful on the third try sometimes. We are facing an ECONNRESET error while requesting POST https://apple-pay-gateway.apple.com/paymentservices/startSession and an error message “Payment not completed” on the client side
Error: read ECONNRESET at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -104,
code: 'ECONNRESET',
config: {
url: 'https://apple-pay-gateway.apple.com/paymentservices/startSession',
method: 'post',
data: '{"merchantIdentifier":"merchant.com.xxxxxxxx","displayName":"xxxxxxxxxx","initiative":"web","initiativeContext":"xxxxxxxx.xxx","domainName":"xxxxxxxx.xxx"}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'User-Agent': 'axios/0.19.2',
'Content-Length': 191
}
},
...
response: undefined,
isAxiosError: true,
Client side code:
applePaySession.onvalidatemerchant = async (event) => {
try {
const data = {
url: event.validationURL,
method: 'post',
body: {
merchantIdentifier,
displayName,
initiative: "web",
initiativeContext: window.location.hostname
},
json: true,
}
const merchantSession = await this.$axios.$post('/apple_pay_session', data);
if (merchantSession && merchantSession.merchantSessionIdentifier) {
applePaySession.completeMerchantValidation(merchantSession)
} else {
applePaySession.abort();
}
} catch (error) {
logReqError(error)
applePaySession.abort();
}
};
Server side:
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
cert: fs.readFileSync(`uploads/apple_pay/${id}/certificate.pem`),
key: fs.readFileSync(`uploads/apple_pay/${id}/private.key`)
});
const sessionRes = await axios({
url: request.body.url,
method: request.body.method.toLowerCase(),
data: request.body.body,
headers: {'Content-Type': 'application/json'}, httpsAgent
})
We checked the status of Merchant Domain - it's verified, Apple Pay Payment Processing Certificate and Apple Pay Merchant Identity Certificate are valid. I also checked project code with the official documentation, as well as with other sources.
I hope anyone has had a similar problem. Any code samples or guesses will be helpful anyway

NotFound error when calling flights date API

I have been using NodeJS library for querying the price of the chepeast flight for a route, for next 60 days. Even after switching to production environment, the API throws 404 error (details mentioned below) for some common routes like SFO to YYC.
Do let me know how I can resolve this.
NotFoundError {
response: Response {
headers: {
date: 'Tue, 19 Oct 2021 17:09:32 GMT',
'content-type': 'application/vnd.amadeus+json',
'content-length': '263',
connection: 'close',
'ama-internal-message-version': '14.1',
'ama-request-id': '00010UI9218IBV',
'ama-gateway-request-id': 'rrt-0b7b1036c139b8050-a-eu-4707-50043169-1',
'access-control-allow-headers': 'origin, x-requested-with, accept, Content-Type, Authorization',
'access-control-max-age': '3628800',
'access-control-allow-methods': '*',
server: 'Amadeus',
'access-control-allow-origin': '*'
},
statusCode: 404,
request: Request {
host: 'api.amadeus.com',
port: 443,
ssl: true,
scheme: 'https',
verb: 'GET',
path: '/v1/shopping/flight-dates',
params: [Object],
queryPath: '/v1/shopping/flight-dates?origin=SFO&destination=YYC&departureDate=2021-10-19%2C2021-12-
18&oneWay=true&viewBy=DATE',
bearerToken: '[REDACTED]',
clientVersion: '5.7.0',
languageVersion: '14.16.1',
appId: null,
appVersion: null,
headers: [Object]
},
body: '{"errors":[{"status":404,"code":6003,"title":"ITEM/DATA NOT FOUND OR DATA NOT EXISTING","detail":"No price result found"},{"status":404,"code":6003,"title" :"ITEM/DATA NOT FOUND OR DATA NOT EXISTING","detail":"No price results found for input combined criteria"}]}',
result: { errors: [Array] },
data: undefined,
parsed: true
},
description: [
{
status: 404,
code: 6003,
title: 'ITEM/DATA NOT FOUND OR DATA NOT EXISTING',
detail: 'No price result found'
},
{
status: 404,
code: 6003,
title: 'ITEM/DATA NOT FOUND OR DATA NOT EXISTING',
detail: 'No price results found for input combined criteria'
}
],
code: 'NotFoundError'
}
My code to query the data looks something like this:
const Amadeus = require("amadeus");
var client = new Amadeus({
hostname: "production",
clientId: FLIGHT_SEARCH_API_KEY,
clientSecret: FLIGHT_SEARCH_API_SECRET,
});
const response = await client.shopping.flightDates.get({
origin,
destination,
departureDate: `${currentDate},${lastDate}`,
oneWay: true,
viewBy: "DATE",
});
The Flight Inspiration Search & Flight Cheapest Date Search APIs are built on top of a pre-computed cache. The APIs compute every day the most trending options based on past searches and bookings and fill the cache, which means that the cache is dynamic. If you need to get access to a full inventory of Amadeus you need to use the live Flight Offers Search API.

Problems connecting Service Account to Admob API with Google-Auth-Library

I've been trying to connect to Admob API from an AWS Lambda to extract some values from reports automatically from time to time. I've successfully got google-auth-library-nodejs to a layer and I am trying to use it to connect to Admob API.
I've made sure to give my Service account an Owner role and I've added the necessary GOOGLE_APPLICATION_CREDENTIALS path to the environement variables.
This is the code that I've added to my Lambda:
const {GoogleAuth} = require('google-auth-library');
exports.handler = (event, context, callback) => {
async function main() {
const auth = new GoogleAuth({
scopes: ['https://www.googleapis.com/auth/admob.report'],
});
const client = await auth.getClient();
//console.log("client", JSON.stringify(client));
const url = `https://admob.googleapis.com/v1/accounts`;
const res = await client.request({ url });
console.log("res: ", JSON.stringify(res.data));
}
main().catch(console.error);
};
When I run the code, I get the following error:
ERROR GaxiosError: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
at Gaxios._request (/opt/nodejs/node_modules/gaxios/build/src/gaxios.js:85:23)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async JWT.requestAsync (/opt/nodejs/node_modules/google-auth-library/build/src/auth/oauth2client.js:350:18)
at async main (/var/task/index.js:97:19) {
response: {
config: {
url: 'https://admob.googleapis.com/v1/accounts',
headers: [Object],
params: [Object: null prototype] {},
paramsSerializer: [Function: paramsSerializer],
validateStatus: [Function: validateStatus],
responseType: 'json',
method: 'GET'
},
data: { error: [Object] },
headers: {
'alt-svc': 'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
'cache-control': 'private',
connection: 'close',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Wed, 26 Feb 2020 18:41:51 GMT',
server: 'ESF',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0'
},
status: 401,
statusText: 'Unauthorized',
request: { responseURL: 'https://admob.googleapis.com/v1/accounts' }
},
config: {
url: 'https://admob.googleapis.com/v1/accounts',
headers: {
Authorization: 'Bearer [Removed]',
'User-Agent': 'google-api-nodejs-client/5.10.1',
'x-goog-api-client': 'gl-node/12.14.1 auth/5.10.1',
Accept: 'application/json'
},
params: [Object: null prototype] {},
paramsSerializer: [Function: paramsSerializer],
validateStatus: [Function: validateStatus],
responseType: 'json',
method: 'GET'
},
code: 401,
errors: [
{
message: 'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
domain: 'global',
reason: 'unauthorized'
}
]
}
I've been trying to find my mistake by searching on google, stack overflow, reading tutorials about connecting to Admob API as well as reading the library's code. I would really appreciate if someone could point me towards a solution.
The problem is you are trying to use a service account where OAuth User Credentials are required. You will need to implement the OAuth 2 Flow where the user enters their Google username and password.
AdMob: Authorization for the request
Refer to the following Google example on how to create a node.js OAuth 2 client.
https://github.com/googleapis/google-auth-library-nodejs#oauth2

Google Cloud Function - SendGrid - 400 Bad Request

I'm trying to send an email using SendGrid in my Google Cloud Function. I have my key in the Firebase environment variables, so that's present.
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
Here is my GCF .ts code:
Code
const msg = {
to: to,
from: from,
subject: 'Email Subject',
content: [{
type: "text/html",
value: body
}]
};
await sgMail.send(msg)
.then(r => {
console.log(r);
});
When I trigger the function and check my logs, this is the error I get:
Error
error: { Error: Bad Request
at ResponseError (node_modules/#sendgrid/mail/node_modules/#sendgrid/helpers/classes/response-error.js:19:5)
at Request.http [as _callback] (node_modules/#sendgrid/mail/node_modules/#sendgrid/client/src/classes/client.js:124:25)
at Request.self.callback (node_modules/#sendgrid/mail/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (node_modules/#sendgrid/mail/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (node_modules/#sendgrid/mail/node_modules/request/request.js:1083:12)
at IncomingMessage.g (events.js:292:16)
code: 400,
message: 'Bad Request',
response:
{ headers:
{ server: 'nginx',
date: 'Sun, 16 Dec 2018 16:27:56 GMT',
'content-type': 'application/json',
'content-length': '402',
connection: 'close',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
body: { errors: [Object] } } }
Does anyone have any familiarity with this error? It mentions CORS, but that makes no sense, because it's a cloud function, not browser. The SendGrid API isn't that great, it mostly goes over the field names and provides no examples. Thanks for any help provided!
EDIT
Just to update the question, in the front end response I send myself I found a different error than the console.log(error) in the GCF logs:
"Email failed: Bad Request (400)
The from object must be provided for every email send.
It is an object that requires the email parameter,
but may also contain a name
parameter. e.g. {"email" : "example#example.com"} or
{"email" : "example#example.com", "name" : "Example Recipient"}.
from.email
http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from"
EDIT 2: SOLUTION
My from email source comes from a document in Firestore, and I was trying to get a field that didn't exist because I was querying the wrong document, therefore from was undefined. Corrected it, as well as removed "content" in the msg object per the suggestion / answer below, and everything works fine.
According to the documentation ...the msg has the wrong elements:
const sg = require('#sendgrid/mail');
sg.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sg.send(msg).then(() => {
/* assume success */
})
.catch(error => {
/* log friendly error */
console.error(error.toString());
/* extract error message */
const {message, code, response} = error;
/* extract response message */
const {headers, body} = response;
});

Azure Insert failed in database but query works

I am trying to do an Insert/replace :
insertOrReplaceEntity('myusertables', task, function(error)
it always goes to error code indicating that insertion did not happen.
How to debug this in Azure?
I am using the Azure emulator and have in the code:
var account = azure.ServiceClient.DEVSTORE_STORAGE_ACCOUNT;
var accountKey = azure.ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY;
I get PUT failed with 403.
{ error:
{ [Error: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctl
including the signature.]
code: 'AuthenticationFailed',
message: 'Server failed to authenticate the request. Make sure the value of Authorization header is formed correc
y including the signature.' },
response:
{ isSuccessful: false,
statusCode: 403,
body:
{ '#': [Object],
code: 'AuthenticationFailed',
message: [Object] },
headers:
{ 'content-length': '356',
'content-type': 'application/xml',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Mon, 12 Nov 2012 20:57:10 GMT' },
md5: undefined } }
As Described here the storage emulator does not support Insert-Or-Replace Entity or Insert-Or-Merge Entity, known as upsert features. That's why when you use insertOrReplaceEntity in your code it return an error. If you have to verify the code, you may need to check it with the real Azure Table Storage.

Resources