Meteor slingshot file upload to Google Cloud Storage internal server error - meteor

I am trying to upload files using edgee:slingshot, but I have several errors. I have did everything as described in github page. This is my settings on server:
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective("myFileUploads", Slingshot.GoogleCloud, {
bucket: 'dossum-app',
GoogleAccessId: "GOOGXXXX",
GoogleSecretKey: "qZEsLZ/NiXXXXXXXXXXXXUW8NVjSvRb8SgdxXXXXX2",
acl: 'bucket-owner-full-control',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
return user.username + '/' + file.name;
}
});
And this is cors.json:
[{"origin": ["http://localhost:3000", "http://qnekt.zehinz.com"], "responseHeader": ["Origin", "Accept", "X-Requested-With", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token"], "method": ["GET", "HEAD", "DELETE", "PUT", "POST", "HEAD"], "maxAgeSeconds": 3600}]
If I run with above configuration I get this error without any details: {error: 500, reason: "Internal server error"....
I have tried to comment this line: //GoogleSecretKey:"qZEsLZ/NiEkXo641XHIUW8NVjSvRb8SgdxIyYcV2"
This time I receive this error:
{error: "Forbidden - 403", reason: "Failed to upload file to cloud storage", details: undefined ...
Can anyone please guide me?
Where should I get GoogleAccessId if I am using .pem file instead of GoogleSecretKey?
What should be the cors.json file for file uploading and public reading?

I had troubles with edgee:slingshot and Google Cloud Storage. But this settings now work for me:
//server
Slingshot.GoogleCloud.directiveDefault.GoogleSecretKey = Assets.getText('google-cloud-service-key.pem');
Slingshot.createDirective('avatarUploader', Slingshot.GoogleCloud, {
bucket: 'my_bucket',
GoogleAccessId: 'xxxxxxxxxxxxxx#developer.gserviceaccount.com',
acl: 'public-read',
authorize: function() {
if (!this.userId) {
var message = 'Please login before posting file';
throw new Meteor.Error('Login Required', message);
}
return true;
},
key: function(file) {
var user = Meteor.users.findOne(this.userId);
var ext = file.type.split('/')[1];
return user.username + '/' + randomString(20) + '.' + ext;
}
});
//CORS settings
[
{
"origin": ["*"],
"responseHeader": ["*"],
"method": ["GET", "POST", "PUT", "HEAD"],
"maxAgeSeconds": 3000
}
]
For details look here.

Related

Failed to fetch. Possible Reasons: Cors Network failure URL Scheme

I trying to do a swagger documentation for an Express API and Firebase database, when I make request to my database in local with postman it work, but with the swagger interface I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
For my documentation I use swagger-autogen and swagger-ui-express
there is a example for the login endpoint:
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
cors({
origin: `http://localhost:${port}`,
methods: ["GET", "POST", "DELETE", "PUT", "PATCH"],
credentials: true,
})
);
app.use(helmet());
app.use(morgan("combined"));
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome" });
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerFile, options));
swagger.js
const outputFile = "schemas/swagger.json";
const endpoints = \["routes/auth.js", "routes/menus.js"\];
const doc = {
info: {
version: "1.0.0",
title: "Menus API documentation",
description: "Documentation of MenusAPI",
termsOfService: "http://swagger.io/terms/",
contact: {
email: "contact#toto.com",
},
license: {
name: "Apache 2.0",
url: "http://www.apache.org/licenses/LICENSE-2.0.html",
},
},
servers: \[
{
url: "https://localhost:8081/menusapi/api/v1/",
},
\],
host: "/",
consumes: \["application/json"\],
produces: \["application/json"\],
securityDefinitions: {
OAuth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: process.env.AUTH_UTI,
tokenUrl: process.env.TOKEN_URI,
scopes: {
read: "Grants read access",
write: "Grants write access",
},
},
},
},
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
"#definitions": {
AddUser: userSchema.registration,
Login: userSchema.login,
Menus: menusSchema,
},
};
swaggerAutogen(outputFile, endpoints, doc).then(() =\> {
require("../app");
});
routes/auth.js
router.post("/login", auth.login);
controllers/auth_controller.js
exports.login = async (req, res) =\> {
/\* #swagger.tags = \['Auth'\]
\#swagger.description = 'Service to login';
\#swagger.summary = "Service to login a user to the app";
\#swagger.security = \[{
"OAuth2": \[
'read',
'write'
\]
}\]
\#swagger.responses\[200\] = {
description: 'Login sucess',
schema: {
"message": "Successfully connected!",
"jwt": "A very long token",
"refresh_jwt": "An other long token"
}
}
console error:
throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` +
^
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value
I looked everywhere but I really don't know what to do

linkedin API cannot create campaign

We have got rw_ads permissions for an app. Through that app We have taken access_token with all given permissions.
As mentioned in the documentation, we have rw_ads permission, but If we try to create/update campaign we are getting the below error.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: POST /adCampaignsV2/sdafnk",
"status": 403 }
var request = require("request");
var options = { method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2/sdafnk',
headers:
{ 'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json' },
body:
{ patch:
{ '$set':
{ runSchedule: { end: 1548405000000, start: 1547713800000 },
status: 'ACTIVE' } } },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Code for creation of campaign is mentioned below
var request = require("request");
var options = {
method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2',
headers: {
'Authorization': 'Bearer <accessToken>',
'Content-Type': 'application/json'
},
body: {
account: 'urn:li:sponsoredAccount:<accountId>',
audienceExpansionEnabled: false,
costType: 'CPM',
creativeSelection: 'OPTIMIZED',
dailyBudget: { amount: '200', currencyCode: 'INR' },
locale: { country: 'IN', language: 'en' },
name: 'Campaign text ad test',
objectiveType: 'WEBSITE_TRAFFIC',
offsiteDeliveryEnabled: false,
runSchedule: { end: 1547708400000, start: 1547967600000 },
type: 'TEXT_AD',
unitCost: { amount: '10', currencyCode: 'INR' },
status: 'PAUSED'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When you perform a partial update, the header X-RestLi-Method must be included in the request and set to PARTIAL_UPDATE.
Also if you use implicit grant-type, check if you have defined the scope correctly at the start. if you use client-credentials grant-type check if the account has the right permissions.
Direct Sponsored Content can be created by:
Ad Account Users with a role higher than VIEWER. Organization users
with DIRECT_SPONSORED_CONTENT_POSTER or ADMINISTRATOR roles.
also the code you added in this question is for Reactivating a campaign. not for updating/creating one.

Meteor onCreateUser generates 403 Signup Forbidden

I've seen several examples of onCreateUser for manually registering a user and from what I can tell all of my code appears OK, but I continue to receive the Signups forbidden [403] error upon creation. I've also looked at the documentation as per http://docs.meteor.com/#/full/accounts_createuser. Thanks everyone for your help.
Here's what I have: ROOT>client>registration.js
Template.registrationStep2.events({
'submit form': function(e, template) {
e.preventDefault();
var institutionID = template.find('#institutionID').value;
var institutionRole = template.find('#institutionRole').value;
var institutionName = template.find('#institutionName').value;
var login = template.find('#login').value;
var firstName = template.find('#firstName').value;
var lastName = template.find('#lastName').value;
var email = template.find('#email').value;
var password = template.find('#password').value;
var profile = {
firstName: firstName,
lastName: lastName,
role: institutionRole,
institutionID: institutionID
}
Accounts.createUser({
username: login,
email: email,
password: password,
profile: profile
}, function(error){
if (error){
Meteor.log.error("Error Creating User", error);
} else {
Session.set("flashType", "success");
Session.set("flashMessage", "Your account has been created.");
Router.go('registrationComplete');
}
});
} else {
// alert("Need institution");
$('#needInstitutionModal').modal('show');
}
}
});
I have accounts-password and accounts-ui installed and updated to the latest versions.
No matter what I do I receive this error:
I20150709-13:43:17.545(-5)? (13:43:17) [ERROR] - Object:
I20150709-13:43:17.546(-5)? {
I20150709-13:43:17.546(-5)? "time": "2015-07-09T18:43:17.543Z",
I20150709-13:43:17.546(-5)? "level": "ERROR",
I20150709-13:43:17.546(-5)? "message": "Error Creating User",
I20150709-13:43:17.546(-5)? "userId": null,
I20150709-13:43:17.546(-5)? "additional": {
I20150709-13:43:17.546(-5)? "error": 403,
I20150709-13:43:17.546(-5)? "reason": "Signups forbidden",
I20150709-13:43:17.546(-5)? "message": "Signups forbidden [403]",
I20150709-13:43:17.547(-5)? "errorType": "Meteor.Error"
I20150709-13:43:17.547(-5)? }
I20150709-13:43:17.547(-5)? }
Figured it out.
In order to do this I had to move the Accounts.createUser function to the server side (server.js side in server folder) and call it as a Meteor.method call.

invalid_grant Google OAuth

I am trying to authentiate through Google's OAuth, but I'm having problems establishing a connection to their API
My client code:
'click #addChannel': function (event) {
event.preventDefault();
var userId = Meteor.userId();
var options = {
requestPermissions: [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtubepartner',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
],
requestOfflineToken: true
};
Google.requestCredential(options, function(token) {
Meteor.call('userAddOauthCredentials', userId, token, function(error, result) {
if (error) {
throw error;
}
console.log(result);
});
});
My server code:
userAddOauthCredentials: function(userId, token) {
check(userId, String);
check(token, String);
var config = ServiceConfiguration.configurations.findOne({service: 'google'});
if (!config) {
throw new ServiceConfiguration.ConfigError();
}
console.log(token, config);
var endpoint = 'https://accounts.google.com/o/oauth2/token';
var params = {
code: token,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: OAuth._redirectUri('google', config),
grant_type: 'authorization_code',
};
try { <------------------------------------------------------ this fails
response = HTTP.post(endpoint, { params: params });
} catch (err) {
throw _.extend(new Error("(first) Failed to complete OAuth handshake with Google. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("(second) Failed to complete OAuth handshake with Google. " + response.data);
} else {
return {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in,
idToken: response.data.id_token
};
}
The above throws a [400] { "error" : "invalid_grant" } error.
Most of the above code I got from how the meteor accounts-google packages logs in a user (which works fine in my application). Link to that:
https://github.com/meteor/meteor/blob/87e3c6499d5eacce62f10faefe9ce49c77bb03ee/packages/google/google_server.js
Any advice on how to proceed from here?
Much appreciated
UPDATE1:
I get these warnings in my log
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.533(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.534(1) (oauth_server.js:398) Error in OAuth Server: Match error: Expected string, got undefined
You have to parse your var params to application/x-www-form-urlencoded. Please find the below code to parse as i done in php
$fields_string="";
foreach($params as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
Now the $filed_string will contained the parse of params array.

How do request to external resource in Meteor?

I need get data from external service. It has API. This is example:
http://portal.example.com/portal.api?l=username&p=keyphrase&act=brand_by_nr&nr=kl2&alt
Parameters are:
"l" - login, "p" - password, "act" - function to execute, "nr" - part number
I try connect by Meteor http.This is my server code:
var sources = {
mskv: {
url: "http://portal.example.com/portal.api",
auth: { l: "mylogin", p: "cBKoTyalCgbOQb37NG6sbb0qv2I0Q4PmWRJIJMWpOhCPFombqeDv7fBhdkjsdhkjah" },
params: { act: "brand_by_nr", nr: null }
}
};
Meteor.methods({
doRequest: function(partNumber) {
for (var key in sources) {
var url = sources[key].url;
var authData = sources[key].auth;
var paramsData = sources[key].params;
paramsData.nr = partNumber;
HTTP.call("POST", url, { auth: authData, params: paramsData }, function(err, res) {
if (err) {
throw new Meteor.Error("not-response", "Remote server not responding");
}
return res;
});
}
}
});
This is my client code:
Template.search.events({
"click .search": function(event) {
var partNumber = document.getElementsByClassName("input")[0].value;
Meteor.call("doRequest", partNumber, function(err, res) {
if(err === "not-response") return;
console.log(res);
});
}
});
I have error:
> Exception while invoking method 'doRequest' TypeError: Object
> #<Object> has no method 'indexOf' I20150227-00:01:35.455(3)? at Object._call (packages/http/httpcall_server.js:42:1)
> I20150227-00:01:35.455(3)? at Object._.extend.wrapAsync [as call]
> (packages/meteor/helpers.js:118:1) I20150227-00:01:35.455(3)? at
> [object Object].Meteor.methods.doRequest (app/server/server.js:19:18)
Can you help me, where is my error?
Try
var paramsData = [sources[key].params];
I suspect it's looking for an array there.
In my case auth field is not correct. The true way is auth:"login: password", look as simply string. Second error - auth field is not need. For this service login and password send as parameters { params: {l:"login", p: "password", act: "brand_by_nr" ....} }

Resources