Azure Node SDK - 500 response with filter option - node.js

I am seeing a weird error on the with Azure Node SDK where I get a 500 error back anytime i include anything in the filter attribute of the options parameter. I am using the Usage Details call within the ConsumptionManagementClient class. Code is below:
const credentials = await MsRest.loginWithServicePrincipalSecret(config.appId, config.apiKey, config.tenantId);
let client = new ConsumptionManagementClient(credentials, subscriptionId);
const scope = `/subscriptions/${subscriptionId}`;
const options = { filter: "usageStart ge datetime'2017-10-13T00:00:00.000Z'"};
let usage = await client.usageDetails.list(scope, options);
The above code produces a 500 error(even tried searching for other things another example being "billableQuantity ge 0.001") but it seems to error out no matter what i give it.
The code works fine when i try using another one of the options paramters:
const credentials = await MsRest.loginWithServicePrincipalSecret(config.appId, config.apiKey, config.tenantId);
let client = new ConsumptionManagementClient(credentials, subscriptionId);
const scope = `/subscriptions/${subscriptionId}`;
const options = { top: 50 };
let usage = await client.usageDetails.list(scope, options);
Any ideas? Thanks in advance for the help!

Related

Gmail authentication is failing with MailKit

I'm writing an app that reads email folders and messages from gmail.
I started out with sample code I found for using MailKit, and it was working fine for a while.
Then it just started complaining about the scope I was passing to GoogleAuthorizationCodeFlow. I was using #"https:\mail.google.com" instead of "https://mail.google.com/". I don't understand why the scope was working earlier and then just started getting rejected.
But after fixing the scope, ImapClient.AuthenticateAsync() is now throwing an "Authentication failed" exception.
I can't find any detail in the exception as to why it's failing. I checked my settings on Google Cloud and everything seems to be in order.
Can anyone help point me to where I should look to debug the issue?
I don't know why it's failing after working for a while, so I haven't really tried anything yet.
Here's the function that's failing. The last line below calling _client.AuthenticateAsync is throwing an "Authentication failed." exception.
private async Task<bool> connectToGmailAsync()
{
var clientSecrets = new ClientSecrets
{
ClientId = Server.ClientId,
ClientSecret = Server.ClientSecret
};
var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("CredentialCacheFolder", false),
ClientSecrets = clientSecrets,
Scopes = new[] { "https://mail.google.com/" }
});
// Note: For a web app, you'll want to use AuthorizationCodeWebApp instead.
var codeReceiver = new LocalServerCodeReceiver();
var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver);
var credential = await authCode.AuthorizeAsync(string.Format("{0}#{1}", UserId, Server.Name), CancellationToken.None);
if (credential.Token.IsExpired(SystemClock.Default))
await credential.RefreshTokenAsync(CancellationToken.None);
_oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken);
_client = new ImapClient();
await _client.ConnectAsync("imap." + Server.Name, Server.PortNumber, SecureSocketOptions.SslOnConnect);
await _client.AuthenticateAsync(_oauth2);
return true;
}

google sheets api fails with missing parameter: spreadsheetId

I am trying to work with a google spreadsheet and the spreadsheet API. Following the directions, I have written the following:
const {google} = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: 'keys.json',
scopes: 'https://www.googleapis.com/auth/spreadsheets'
});
const authClientObject = auth.getClient();
const googleSheetInstance = google.sheets({version: 'v4',auth: authClientObject})
const spreadSheetId = 'customsheetid';
const result = googleSheetInstance.spreadsheets.values.get({
spreadSheetId,
range:'sheet1'
})
My problem is that it keeps failing. Any time I run this I get: UnhandledPromiseRejectionWarning: Error: Missing required parameters: spreadsheetId. Everything that I have read and looked at on both the official docs and StackOverflow, my get statement should be written correctly. But clearly, I am missing something and would appreciate any advice.
I needed to change the variable name. I took it from spreadSheetId to spreadsheetId.

getting a parse error and cannot find eslint file

I've realized that you can't send messages directly from the client with the FCM v1 API so now I'm using node.js and I wan't to deploy this cloud function, but I am getting a parse error like so:
This is my function:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { event } = require("firebase-functions/lib/providers/analytics");
admin.initializeApp(functions.config().firebase);
exports.sendNotificationsToTopic =
functions.firestore.document("school_users/{uid}/events/{docID}").onWrite(async (event) => {
let docID = event.after.id;
let schoolID = event.after.get("school_id")
let title = "New Event!!"
let notificationBody = "A new event has been added to the dashboard!!"
var message = {
notification: {
title: title,
body: notificationBody,
},
topic: schoolID,
};
let response = await admin.messaging().sendToTopic(message);
console.log(response);
});
I did some research and found people were getting similar errors with their projects, and answers were saying to update the version of eslint so it picks up on the shorthand syntax, I can't figure out where to find the eslint file to update the version. Does anybody know where I can find this file?
All I needed to do was show my hidden files in my functions directory. Once I seen the .eslintrc.js file, I simply removed a part of a value from the "eslint" key, and the function deployed perfectly fine.

Setting CORS rules using Azure.Storage.Blobs

I'm trying to migrate from the deprecated Microsoft.WindowsAzure.Storage to Azure.Storage. In my API app, I have a method that I call occasionally to programmatically set the CORS rules in my Azure Storage account.
How do I add CORS rules to the properties using the new Azure.Storage.Blobs?
My original code that worked under Microsoft.WindowsAzure.Storage is as follows. In the following code, the _client is an instance of CloudBlobClient. I understand that in Azure.Storage.Blobs, I need to use BlobServiceClient which I now do but as I said, some parts of the following code are not working because some methods/properties are no longer there. I'm sure they're moved somewhere else but I haven't been able to figure out where.
public async Task ConfigureCors()
{
var ALLOWED_CORS_ORIGINS = new List<String> { "http://localhost:49065", "https://myappdomain.com", "https://www.myappdomain", "https://login.microsoftonline.com" };
var ALLOWED_CORS_HEADERS = new List<String> { "x-ms-meta-qqfilename", "Content-Type", "x-ms-blob-type", "x-ms-blob-content-type" };
const CorsHttpMethods ALLOWED_CORS_METHODS = CorsHttpMethods.Get | CorsHttpMethods.Delete | CorsHttpMethods.Put | CorsHttpMethods.Options;
const int ALLOWED_CORS_AGE_DAYS = 5;
var properties = await _client.GetServicePropertiesAsync();
properties.DefaultServiceVersion = "2013-08-15";
await _client.SetServicePropertiesAsync(properties);
var addRule = true;
if (addRule)
{
var ruleWideOpenWriter = new CorsRule()
{
AllowedHeaders = ALLOWED_CORS_HEADERS,
AllowedOrigins = ALLOWED_CORS_ORIGINS,
AllowedMethods = ALLOWED_CORS_METHODS,
MaxAgeInSeconds = (int)TimeSpan.FromDays(ALLOWED_CORS_AGE_DAYS).TotalSeconds
};
properties.Cors.CorsRules.Clear();
properties.Cors.CorsRules.Add(ruleWideOpenWriter);
await _client.SetServicePropertiesAsync(properties);
}
}
Looks like I can get and set properties by changing _client.GetServicePropertiesAsync() to _client.GetPropertiesAsync() but DefaultServiceVersion is no longer there. Also I can't seem to find the right way to set CORS rules.
I'd appreciate your suggestions. Thanks!
You can use the code below when using Azure.Storage.Blobs(I'm using sync method, please change it to async method if you need that):
var properties = blobServiceClient.GetProperties().Value;
properties.DefaultServiceVersion = "xxx";
BlobCorsRule rule = new BlobCorsRule();
rule.AllowedHeaders= "x-ms-meta-qqfilename,Content-Type,x-ms-blob-type,x-ms-blob-content-type";
rule.AllowedMethods = "GET,DELETE,PUT,OPTIONS";
rule.AllowedOrigins = "http://localhost:49065,https://myappdomain.com,https://www.myappdomain,https://login.microsoftonline.com";
rule.MaxAgeInSeconds = 3600; // in seconds
properties.Cors.Add(rule);
blobServiceClient.SetProperties(properties);

How to get groups that user belong to?

Using Graph Service, I have tried to get list of groups that user belong to. Here is my sample code:
var userMemberOf = null;
var userMemberGroups = null;
const GraphService = require('graph-service');
const ClientCredentials = require('client-credentials');
const tenant = 'my-company.com';
const clientId = '0b13aa29-ca6b-42e8-a083-89e5bccdf141';
const clientSecret = 'lsl2isRe99Flsj32elwe89234ljhasd8239jsad2sl=';
const credentials = new ClientCredentials(tenant, clientId, clientSecret);
const service = new GraphService(credentials);
service.get('/users/tnguyen482#my-company.com/memberOf').then(response => {
userMemberOf = response.data;
});
var settings = {
"securityEnabledOnly": true
}
service.post('/users/tnguyen482#my-company.com/getMemberGroups', settings).then(response => {
userMemberGroups = response.data;
});
The data return from both get & post method was an empty list. I have tried another user id but the result is the same. Am I correct when using method memberOf and getMemberGroups to get list of groups that user belong to? Does my sample code correct?
When the user is in no group graph will return an empty result.
Otherwise, when an error occured (e.g. accessDenied or user not found) an corresponding http-status with an errormessage will be returned (more information in the documentation).
The operations you are using seem to be correct.
If you want to rule out that your operations/code is incorrect, you should try executing the operations in the Graph Explorer.
Its a great tool for debugging and you can even login for access to your own data.

Resources