power off virtual guest using softlayer api using Javascript - ibm-cloud

I have tried the softlayer api to do the same which is not letting the VM to be powered off .
api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest//powerOff?
I am adding all the required credentials but it always returns an error sayind resource with id not found.

The error you got is because the virtual server that you want to powerOff does not exist in your account. I suggest you to verify if that VS exists in your account by the portal control.
Or you can use the following rest api:
Method: GET
https://[username]:[apiKey]#api.softlayer.com/rest/v3.1/SoftLayer_Account/getVirtualGuests?objectFilter={"virtualGuests":{"id":{"operation":11111}}}
Replace the 11111 data of the filter for your vs id.
Below there is an example how to powerOff a vs by node.js:
var username = 'set me';
var apikey = 'set me';
var virtualGuestId = 1111111;
var SoftLayer = require('softlayer-node');
var client = new SoftLayer();
client
  .auth(username , apikey)
  .path('Virtual_Guest', virtualGuestId, 'powerOff')
  .get()
  .then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
Reference:
https://www.npmjs.com/package/softlayer-node

Related

Microsoft Graph API - AuthenticationError when accessing mail

I'm currently implementing an Outlook Add-In that should access certain mail fields. So I setup a starter project and set the delegated Mail.Read permission in the Microsoft Azure Active Directory settings and added it to my scope configuration.
However, when I send the request for
graph.microsoft.com/v1.0/me/messages/
I get this as a response:
Error: Bad Request
at IncomingMessage.<anonymous> (C:\Users\zz\public\javascripts\odata-helper.js:53:29)
at IncomingMessage.emit (events.js:322:22)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 400,
bodyCode: 'AuthenticationError',
bodyMessage: 'Error authenticating with resource'
}
I don't understand why this error appears since the user authentication works and I don't have any problems with other Graph Endpoints (e.g. retrieving a list of my OneDrive files from /me/drive/root/children)
I am using this as a codebase:
https://learn.microsoft.com/en-us/office/dev/add-ins/develop/create-sso-office-add-ins-nodejs
I didn't reproduce your issue and graph.microsoft.com/v1.0/me/messages works fine in the sample you shared.
Please refer to my configuration.
In addition to the configuration mentioned in the documentation, I also made the following changes.
Add a Mail.Read Delegated permission in Azure AD app.
Modify the Microsoft Graph endpoint in app.js file. Please note I'm querying the subject property of messages. So I modified the two places: $select=subject&$top=10 and itemNames.push(item['subject']).
app.get('/getuserdata', async function(req, res, next) {
const graphToken = req.get('access_token');
const graphData = await getGraphData(graphToken, "/me/messages", "?$select=subject&$top=10");
if (graphData.code) {
next(createError(graphData.code, "Microsoft Graph error " + JSON.stringify(graphData)));
}
else
{
const itemNames = [];
const oneDriveItems = graphData['value'];
for (let item of oneDriveItems){
itemNames.push(item['subject']);
}
res.send(itemNames)
}
}
In the add-in manifest file "manifest\manifest_local.xml", I add a scope "Mail.Read".
<WebApplicationInfo>
<Id>a7eb1d00-f724-4799-8a46-809f2dba63f8</Id>
<Resource>api://localhost:44355/a7eb1d00-f724-4799-8a46-809f2dba63f8</Resource>
<Scopes>
<Scope>Files.Read.All</Scope>
<Scope>profile</Scope>
<Scope>Mail.Read</Scope>
</Scopes>
</WebApplicationInfo>
In the file routes\authRoute.js, I add the 'Mail.Read' like this:
else {
const [schema, jwt] = authorization.split(' ');
const formParams = {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwt,
requested_token_use: 'on_behalf_of',
scope: ['Files.Read.All', 'Mail.Read'].join(' ')
};
These are all the configurations and I can get the subject of messages in Microsoft Word addin:

google-api-nodejs-client: how to call google+ domain api locally? (by the plusDomains.media.insert)

I am going to use the Nodejs google api client(google-api-nodejs-client) to post a photo to my google+. (I have listed all my code at end of this post.)
Let me introduce a little bit background:
I have created a project on: console.developers.google.com
I have enabled google+ domain API for this project.
I have created credentials for this project as well. (it is a OAuth 2.0 client ID)
I have a little bit experience of using the client (google-api-nodejs-client) and I can post images and files to my google drive by it.
However, posting to google+ photo is different, the auth is the key different. I have tried several different ways, but none of them works.
The api always return me this:
{ [Error: Forbidden]
code: 403,
errors: [ { domain: 'global', reason: 'forbidden', message: 'Forbidden' } ] }
I also found this:
Warning: The Google+ Sign-In button and the plus.login scope used by
Google+ Sign-In, are not currently supported for use with the Google+
Domains API. Requests that are made to the Google+ Domains API using
an authentication token granted for the
www.googleapis.com/auth/plus.login scope, or generated by the
Google+ Sign-In button, will fail.
If it doesn't support the sign-button, what does it support?
This page tell me to add a domain delegation (https://developers.google.com/+/domains/authentication/delegation), but i haven't push my program into any server, i just try to run it locally.
I was wondering if it is possible to use this client to post photo to google+ by run a nodejs program locally?
var CLIENT_ID = "xxxxxxx.apps.googleusercontent.com";
var CLIENT_SECRET = "xxxxxxxx";
var REDIRECT_URL = "https://xxxxxxx";
var readline = require('readline');
var async = require('async');
var google = require('googleapis');
var request = require('request');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getAccessToken (oauth2Client, callback) {
// generate consent page url
var scopes = [
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.read',
'https://www.googleapis.com/auth/plus.stream.write',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.circles.write',
'https://www.googleapis.com/auth/plus.media.upload'
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes, // If you only need one scope you can pass it as string,
key: 'p7UALH460Deqodhvb2zESYya'
});
console.log('Visit the url: ', url);
rl.question('Enter the code here:', function (code) {
// request access token
oauth2Client.getToken(code, function (err, tokens) {
if (err) {
return callback(err);
}
// set tokens to the client
// TODO: tokens should be set by OAuth2 client.
oauth2Client.setCredentials(tokens);
console.dir(tokens);
callback();
});
});
}
getAccessToken(oauth2Client, function () {
var plusDomains = google.plusDomains({ version: 'v1', auth: oauth2Client });
var requestObj = request({url:'http://asset1.cxnmarksandspencer.com/is/image/mands/2643f540b32fe8c6cccdec95b3a2c5239166232f?$editorial_430x430$'});
const Readable = require('stream').Readable;
var iamgeStream = new Readable().wrap(requestObj);
plusDomains.media.insert({
userId: 'me',
collection: 'cloud',
resource: {
name: 'testimage.png',
mimeType: 'image/png'
},
media: {
mimeType: 'image/png',
body: iamgeStream
},
access:{domainRestricted :"true"}
}, callbackFn);
function callbackFn(argument) {
console.dir(argument);
}
});
Thanks you very much!
Peter

MongoJS, Node, MongoLab - How to get the database online

I have created an hybrid application with Ionic, MongoJS, Angular JS (Mean Stack).
My application worked fine, locally. This means my mongod (Mongo Service) and my mongo ran locally on my pc. I also have a server.js (node) which is located locally.
Now I would like to use MongoLab (MongoDB as a Service) to change the location of my database from local to online.
I intented to change just the connection path, but for some reason I receive an undefined through my http get request.
My code:
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
//var db = mongojs('nzbaienfurtdb', ['nzbaienfurtdb']); // This is my old mongojs which ran locally and worked fine.
var databaseUrl = 'mongodb://dbuser:password#ds045604.mongolab.com:45604/nzbaienfurtdb';
var db = mongojs(databaseUrl, ['nzbaienfurtdb']); // database online with MongoLab
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/www"));
app.use(bodyParser.json());
app.get('/nzbaienfurtdb', function (req, res) {
console.log("I received a GET request")
db.nzbaienfurtdb.find(function (err, docs){
console.log(docs);
res.json(docs);
});
});
app.listen(3000);
console.log("server running on 3000");
This is a part of my get request out of a service:
service.js
return {
getUsers: function(){""
$http.get("/nzbaienfurtdb")
.success(function(data, status, headers, config){
headers("Cache-Control", "no-cache, no-store, must-revalidate");
headers("Pragma", "no-cache");
headers("Expires", 0);
users = angular.fromJson(data);
})
.error(function(data, status, headers, config){
console.log('Data could not be loaded, try again later');
})
return users;
}
MongoLab has been setup already.
My questions:
Why do I get an undefined for my http GET Request?
What happens with my server.js file when I want to deploy the Ionic App on for example an Android Phone? Is the server running on the device?
Since I have changed the var db variable i get also the following error message in my chrome console:
--------- ERROR CODE:
SyntaxError: Unexpected end of input
at Object.parse (native)
at Object.fromJson (http://localhost:3000/lib/ionic/js/ionic.bundle.js:8764:14)
at http://localhost:3000/js/userServices.js:23:27
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:15737:11
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at wrappedCallback (http://localhost:3000/lib/ionic/js/ionic.bundle.js:19197:81)
at http://localhost:3000/lib/ionic/js/ionic.bundle.js:19283:26
at Scope.$eval (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20326:28)
at Scope.$digest (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20138:31)
at Scope.$apply (http://localhost:3000/lib/ionic/js/ionic.bundle.js:20430:24)
I hope somebody can help me out, I am fighting now for ages!
Thank you in advance, guys!
This issue has been resolved after ages!
I had to enable the API on the website of mongolab in my configuration.

How do I prevent the user from being asked to grant permissions for a Google Apps Marketplace app that the domain administrator has approved

I've been trying to convert an old style Marketplace app to the new way of doing things, but I keep having the user prompted for authorization when they first follow the Universal Navigation link (the app was installed onto the domain via the 'Test Install Flow' link on the marketplace SDK).
When I request the 'openid email' scopes, the prompt appears, but if I specify a separate scope (instead of, not in addition to 'openid email') that is part of the app, it doesn't prompt the user for auth (unless I request offline access, which I want for parity of features with the previous version, but one problem at a time...).
Sample code using the google api nodejs client:
var http = require('http');
var googleapis = require('googleapis');
var url_parse = require('url');
var OAuth = googleapis.auth.OAuth2;
var client = new OAuth(
CLIENT_ID
CLIENT_SECRET
REDIRECT_URL
);
http.createServer(dispatcher).listen(80);
function dispatcher(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
var url = url_parse.parse(req.url, true);
if(url.pathname === '/auth') {
auth_time(res);
} else if (url.pathname === '/callback') {
console.log('looking good');
client.getToken(url.query.code, function(err, tokens){
console.log(tokens);
client.setCredentials(tokens);
res.end(render_page('yep'));
});
} else {
res.end(render_page('different page'));
console.log(req.url);
}
}
function auth_time(res){
res.end(render_page('<a href="'+client.generateAuthUrl({
scope: 'openid email https://www.google.com/m8/feeds', //Prompts
// scope: 'https://www.google.com/m8/feeds', //Doesn't prompt
include_granted_scopes: 'true',
access_type: 'online'
})+'">Click for auth</a>'));
}
function render_page(contents){
return '<html><head><title>The page</title></head><body>'+contents+'</body></html>';
}
This similar question has an answer suggesting that https://www.googleapis.com/auth/plus.me is added to the list of scopes used on the Marketplace SDK, but that scope is removed on page refresh (I'm guessing it is treated as identical to one or both of https://www.googleapis.com/auth/userinfo.email & https://www.googleapis.com/auth/userinfo.profile which are automatically set as scopes and are not removable.

Error 500 backendError with Gmail API and Google APIs Node Client

I'm trying to use the new Gmail API with the Google API Node client. I created a new project from the developer console, set up a new "Service Account" Client ID, and enabled access to the API.
As a proof of concept, I am simply trying to list the threads in my inbox. When I enable the OAuth 2.0 toggle for the API explorer and enter my email address, the request succeeds and I see a JSON response with data.
Now I try to do the same in Node:
var googleapis = require('googleapis');
var SERVICE_ACCOUNT_EMAIL = '...SNIP...';
// generated by: openssl pkcs12 -in ...SNIP...p12 -out key.pem -nocerts -nodes
var SERVICE_ACCOUNT_KEY_FILE = 'key.pem';
var jwt = new googleapis.auth.JWT(
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_KEY_FILE,
null,
['https://www.googleapis.com/auth/gmail.readonly']);
googleapis
.discover('gmail', 'v1')
.execute(function(err, client) {
jwt.authorize(function(err, result) {
if(err) console.error(err);
else console.log(result);
client.gmail.users.threads.list()
.withAuthClient(jwt)
.execute(function(err, result) {
if(err) console.error(err);
else console.log(result);
});
});
});
First I print the results of the authorize() call, which looks like it returns a token, so I think I have all the OAuth stuff setup properly:
{ access_token: '...SNIP...',
token_type: 'Bearer',
expires_in: 1404277946,
refresh_token: 'jwt-placeholder' }
Then I try to actually use the API, but I get an error:
{ errors:
[ { domain: 'global',
reason: 'backendError',
message: 'Backend Error' } ],
code: 500,
message: 'Backend Error' }
At this point, I don't know what else to try. I think the OAuth stuff is working properly, because I haven't gotten any authentication errors. I also think the API itself is working and my account is fine, because I can use it through the API Explorer. I don't see any indication that the Node library is at fault either. In short, I have no idea what the problem is. Any ideas?
You are using the Service Account to authenticate your requests to GMail. Your Service Account will not have a Gmail as far as I know, only users have GMail. For this reason you will need to do the OAuth2 flow with the user (see here for example).