MemberOf in Graph Me api azure AD - javascript

I am trying to get the member groups of the user to whom user belongs using azure graph api but it is not returning memberof in the api. I am using auth0 for the authentication.
Here is the java script code which I am using.
function(accessToken, ctx, cb) {
const jwt = require('jsonwebtoken#7.1.9');
console.log('azure - retrieve user profile');
// Retrieve the profile from Azure
request.get(
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf', {
headers: {
'Authorization': 'Bearer ' + accessToken,
},
json: true
},
function(e, r, profile) {
if (e) {
console.log('azure - error while retrieving user profile:');
console.log(e);
return cb(e)
}
if (r.statusCode !== 200) {
console.log('azure - error while retrieving user profile: ' + r.statusCode);
return cb(new Error('StatusCode: ' + r.statusCode));
}
console.log('azure - retrieved user profile.');
// Get the tenant id from the access token
let decodedToken = jwt.decode(accessToken);
let auth0Profile = {
user_id: profile.id,
given_name: profile.givenName,
family_name: profile.surname,
email: profile.mail || profile.otherMails[0] || profile.userPrincipalName,
email_verified: true,
name: profile.givenName + ' ' + profile.surname,
tenant_id: decodedToken.tid,
identification_value: decodedToken.tid,
user_principal_name: profile.userPrincipalName,
user_department: profile.department,
user_member: profile.memberOf
};
cb(null, auth0Profile);
}
);
}
I have added scope (User.Read Directory.Read.All) in Auth0 for the api call.
Can some one let me know why I am not getting memberOf?

If you want to get member groups of the user, along with multiple attributes, the query will not return the expected results.
I tried checking the same query in Microsoft Graph Explorer.
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf'
Even
for that, except memberOf, all objects displayed:
For getting memberOf, you have to query separately like below:
https://graph.microsoft.com/v1.0/me/memberOf
So, for the workaround, you can make use of the above query by giving it separately without querying with other attributes.
Also please make sure to add GroupMember.Read.All permissions in the scope as mentioned in this Microsoft Doc.
Please find below links if they are helpful: Ref1, Ref2

Related

Spotify api add track to playlist

I am using ReactJS and trying to make simple site using the Spotify api.
I am also using the js package spotify-web-api-js. I have succeeded to get the current song playing and able to show it in the browser.
getNowPlaying(){
spotifyApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
albumArt: response.item.album.images[0].url
}
});
})
}
//this is from the github link above
Constr.prototype.getMyCurrentPlaybackState = function(options, callback) {
var requestData = {
url: _baseUri + '/me/player'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};
But the problem I am facing is to add a track to my playlist. I have tried to use the function replaceTracksInPlaylist from spotify-web-api-js but I cant manage to get it to work, I always get the 403 Forbidden error.
addToPlayList(){
spotifyApi.addTracksToPlaylist(listID, listOfSongID, callback);
}
//this is from the github link above
Constr.prototype.replaceTracksInPlaylist = function(playlistId, uris, callback) {
var requestData = {
url: _baseUri + '/playlists/' + playlistId + '/tracks',
type: 'PUT',
postData: { uris: uris }
};
return _checkParamsAndPerformRequest(requestData, {}, callback);
};
The first example also requires authentication as a access token but why does it not work when adding to a playlist?
I have also changed the scopes to the correct ones that the api documentation says i should use, playlist-modify-public and playlist-modify-private
var scope = 'playlist-modify-public playlist-modify-private user-read-private user-read-email user-read-playback-state';
I can test the api call from the api documentation site and insert my oauth token, track and the playlist id there, and that works fine, I also get this back from the call. I cant think of anything else to try and need some help figuring out the next step.

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

Youtube API returns account details of a different user

I am using google's API for node.js
https://www.npmjs.com/package/googleapis
I am trying to get an array of all channels which belong to the person
who logged into my website with his google account.
I am using this scope for this matter:
''https://www.googleapis.com/auth/youtube.readonly'
Now here is part of my code:
app.get("/oauthcallback", function(req, res) {
//google redirected us back in here with random token
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) { //let's check if the query code is valid.
if (err) { //invalid query code.
console.log(err);
res.send(err);
return;
}
//google now verified that the login was correct.
googleAccountVerified(tokens, res); //now decide what to do with it
});
});
function googleAccountVerified(tokens, res){ //successfully verified.
//user was verified by google, continue.
oauth2Client.setCredentials(tokens); //save tokens to an object
//now ask google for the user's details
//with the verified tokens you got.
youtube.channels.list({
forUsername: true,
part: "snippet",
auth: oauth2Client
}, function (err, response) {
if(err) {
res.send("Something went wrong, can't get your google info");
return;
}
console.log(response.items[0].snippet);
res.send("test");
});
}
Now, in this console.log:
console.log(response.items[0].snippet);
I am getting the same info, no matter what account I am using to log into my website:
{ title: 'True',
description: '',
publishedAt: '2005-10-14T10:09:11.000Z',
thumbnails:
{ default: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/1.jpg?v=51448e08' },
medium: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/mq1.jpg?v=51448e08' },
high: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/hq1.jpg?v=51448e08' } },
localized: { title: 'True', description: '' } }
if I do console.log(response) which is the entire response
I get:
{ kind: 'youtube#channelListResponse',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/ch97FwhvtkdYcbQGBeya1XtFqyQ"',
pageInfo: { totalResults: 1, resultsPerPage: 5 },
items:
[ { kind: 'youtube#channel',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/bBTQeJyetWCB7vBdSCu-7VLgZug"',
id: 'UCG9p-zLTq1mO1KAwzN2h0YQ',
snippet: [Object] } ] }
So, two problems here:
1) How do I get an array of owned channels by the logged user,
inside the array I need objects which will represent each channel and basic info like channel name, profile pic.
2) why am I getting the info of some random youtube channel called "True"
Not sure about question one but for question two you get the information for the channel called true because you are asking for it. forUsername: true
I would hope that once you correct this the response may contain more than one channel if the username has more than one.
Just a follow up to the question about basic info.
You dont use Youtube API to get an account's profile information. Instead, try Retrieve Profile Information with G+:
To retrieve profile information for a user, use the people.get API method. To get profile information for the currently authorized user, use the userId value of me.
JavaScript example:
// This sample assumes a client object has been created.
// To learn more about creating a client, check out the starter:
// https://developers.google.com/+/quickstart/javascript
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log('Retrieved profile for:' + resp.displayName);
});
});
Google Sign-in for Websites also enables Getting profile information:
After you have signed in a user with Google using the default scopes, you can access the user's Google ID, name, profile URL, and email address.
To retrieve profile information for a user, use the getBasicProfile() method. For example:
if (auth2.isSignedIn.get()) {
var profile = auth2.currentUser.get().getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}

How to prevent current user get notified?

I'm making an app that allows user to like and comment on other user post. I'm using Parse as my backend. I'm able to notified user everytime their post liked or commented. However if current user like or comment on their own post this current user still notified. How can I prevent this?
Here is the js code that I use:
Parse.Cloud.afterSave('Likes', function(request) {
// read pointer async
request.object.get("likedPost").fetch().then(function(like){
// 'post' is the commentedPost object here
var liker = like.get('createdBy');
// proceed with the rest of your code - unchanged
var query = new Parse.Query(Parse.Installation);
query.equalTo('jooveUser', liker);
Parse.Push.send({
where: query, // Set our Installation query.
data: {
alert: message = request.user.get('username') + ' liked your post',
badge: "Increment",
sound: "facebook_pop.mp3",
t : "l",
lid : request.object.id,
pid: request.object.get('likedPostId'),
lu : request.user.get('username'),
ca : request.object.createdAt,
pf : request.user.get('profilePicture')
}
}, {
success: function() {
console.log("push sent")
},
error: function(err) {
console.log("push not sent");
}
});
});
});
If I understand the context of where this code is correctly,
I recommend checking
if request.user.get("username") != Parse.CurrentUser.get("username")
Before sending out the push notification
Where is your cloud function being called from? If you're calling it from your ios code, then before you call the cloud code function, just prelude it with something like this:
if (PFUser.currentUser?.valueForKey("userName") as! String) != (parseUser.valueForKey("userName") as! String)

How to access gmail API?

I generate my JWT, if my token is correct why dont work ? in Google Developers Console i enabled gmail plus youtube and other API, in credentials generate and download json
{
"private_key_id": "22dcf",
"private_key": "-----BEGIN PRIVATE KEY-----(remove)-----END PRIVATE KEY-----\n",
"client_email": "vgfjjc6#developer.gserviceaccount.com",
"client_id": "jc6.apps.googleusercontent.com",
"type": "service_account"
}
first generate token
var sHead=JSON.stringify({"alg":"RS256","typ":"JWT"});
var iat=timeStampf();
var exp=iat+3600;
var sPayload=JSON.stringify({
"iss":client_email,
"scope":scope,//gmail scope https://mail.google.com/
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":exp,
"iat":iat
});
var sJWS = KJUR.jws.JWS.sign("RS256", sHead,sPayload, private_key);
var paramstoken="grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-ty
pe%3Ajwt-bearer&assertion="+sJWS
getToken("POST","/oauth2/v3/token",paramstoken,jsonData,replier);
/*rest petition return 200 OK
{
"access_token" : "1bHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
"token_type" : "Bearer",
"expires_in" : 3600
}*/
next i test my token
function testToken(accessToken,replier)
{
// /gmail/v1/users/me/messages /plus/v1/people/me
var client = vertx.createHttpClient().host(urlbase).port(443).ssl(true).maxPoolSize(10);
var request = client.request("GET", "/gmail/v1/users/me/messages", function(resp) {
console.log('server returned status code: ' + resp.statusCode());
console.log('server returned status message: ' + resp.statusMessage());
resp.bodyHandler(function(body) {
replier(JSON.parse(body.toString()));
});
});
request.headers()
.set("Content-type", contentType)
.set("Authorization", "Bearer "+accessToken);
request.end();
client.close();
}
if i use google+ scope and this petition the answer is 200 ok
https://www.googleapis.com/auth/plus.me /plus/v1/people/me
{
"kind":"plus#person",
"etag":"\"LR9iFZQGXELLHS07eQ\"",
"objectType":"person","id":"1149981343","displayName":"","name":{"familyName":"","givenName":""},"image":{"url":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50","isDefault":true},"isPlusUser":false,"language":"en_US","circledByCount":0,"verified":false}
but if i try with gmail
{"error":{"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}],"code":400,"message":"Bad Request"}}
In case of GMail, you are accessing a particular user's data, so when creating the JWT, you need to specify the user whom you are trying to impersonate, i.e. the user whose mailbox you want to access.
You can do this using the sub:"User's email address parameter" when forming the JWT Claim set
var sPayload=JSON.stringify({
"iss":client_email,
"sub":USER_EMAIL_ADDRESS
"scope":scope,//gmail scope https://mail.google.com/
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":exp,
"iat":iat
});

Categories

Resources