How to get a slack user by email using users.info API? - slack-api

I'm trying to use Slack's users.info API to retrieve users information, but I need to find users by email, is there a way to do that?

Yes!
https://slack.com/api/users.lookupByEmail
Using this we can find a user if email id is available.
More : https://api.slack.com/methods/users.lookupByEmail

Currently you can only look up users with users.info by their ID.
An alternative solution to your problem would be to call users.list and filter within your client by the profile.email for whichever email you're looking for.

An undocumented API can do this job:
https://slack.com/api/auth.findUser?team=&email=&token=xoxp-XXXXXXXXX

If this is being done on behalf of a Slack slash command, one can configure the command to expand #username, #channels, etc...
This can be done under the command section of the Slack app. See the following screenshot:

You should use this scope users:read.email, the users:read is no longer a sufficient scope for email field.
Check this to get more infos: https://api.slack.com/scopes/users:read.email
That's worked for me as wanted !

This was useful for me.
My setup: I am part of an enterprise, so the legacy token does not have users:read.email scope to it.
Solution: I created an app with users:read.email scope and other scopes needed. Got the app approved from my admin, installed the app to my workspace, retrieved the OAuth token, used it with https://slack.com/api/users.lookupByEmail.

you can get the userid with message.user from main calling method
getUsername(userID).then((output) => { username = output.user.name });
function getUsername(userid){
return new Promise((resolve, reject) => {
//get token from https://api.slack.com/methods/users.info
options.uri = "https://slack.com/api/users.info?token=********&userid=" +userid+ "&pretty=";
rp(options).then(function (body) {
resolve(body);
console.log('Retrieved Info slack --- ' + JSON.stringify(body));
})
.catch(function (err) {
resolve(err);
console.log('aborted - slack ' + JSON.stringify(err));
});
});
}
refer link : https://github.com/hassifow/Slack.API-User.info/blob/master/LambdaFunction.js

https://api.slack.com/methods/users.lookupByEmail
POST https://slack.com/api/users.lookupByEmail?email=seunggabi#gmail.com
form-data
token=xoxb-############-#############-$$$$$$$$$$$$$$$$$$$$$$$$

Related

Discord Oauth2 receiving 'invalid client' error

I had Discord Oauth2 implemented so that my users could log into my website by authenticating through Discord. For months, everything worked great and now all of the sudden it stopped working.
Per Discord's oauth2 instructions,https://discordapp.com/developers/docs/topics/oauth2#shared-resources, I am able to successfully acquire the access code that is meant to be traded for the access token. However, when I try to receive the access token I receive an 'invalid_client' error.
First, I am hitting this endpoint:
https://discordapp.com/api/oauth2/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Flogin%2Fdiscord%2Fcallback&response_type=code&scope=identify%20email%20gdm.join
which successfully returns the following:
http://localhost:5000/login/discord/callback?code={some_access_code}
The access code is then sent back to discord to obtain the access token. Here is the code that is failing:
export function getDiscordAccessToken(accessCode, call) {
const redirect = call === 'login' ? process.env.DISCORD_LOGIN_REDIRECT : process.env.DISCORD_CONNECT_REDIRECT
return new Promise((resolve, reject) => {
axios
.post(
`https://discordapp.com/api/oauth2/token?client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=authorization_code&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join`
)
.then(res => {
resolve(res.data)
})
.catch(err => {
// log error to db
console.log("Here is your error: ", err.response)
reject(err.response)
})
})
}
This code was working for months with no problems. Then, all of the sudden it stopped working. I even checked the Discord change logs which can be found here, https://discordapp.com/developers/docs/change-log, but I found no reference to authentication changes.
Any help you can provide is greatly appreciated!
The query parameters should be in the BODY of the POST request, not the URL for the oauth/token url.
Discord recently pushed a update to the oAuth2 which makes it confine more with the standard. This means they no longer support parameters in the URL for POST, but instead require them to be in the body and form encoded (basically the same, but in the body and without the leading ?).
So you basically need (not tested):
axios.post(
`https://discordapp.com/api/oauth2/token`,
`client_id=${process.env.DISCORD_CLIENTID}&client_secret=${process.env.DISCORD_SECRET}&grant_type=client_credentials&code=${accessCode}&redirect_uri=${redirect}&scope=identify%20email%20gdm.join`
)
I know the question has already been answered, but in my case I copied a wrong secret key. Just make sure that you copy the right one.
Secret Key is located under OAuth2 Tab and not under General Information tab on discord developer's dashboard.

How do you use an iOS Google ID Token to fetch a user's full profile from the backend (Node JS)?

I'm using the Google Login iOS SDK to login, then passing GIDGoogleUser.authentication.idToken to the server, which I'm then verifying in Node JS. The verification in the code below works fine. "payload" var ends up being correct with basic information about the user.
How do I translate the idToken into credentials that I can use to git the people.get endpoint? (I want to know whether the user is using the default Google profile photo or not, and that is available from the people.get endpoint.) This does not seem to be documented anywhere.
https://developers.google.com/people/api/rest/v1/people/get
var auth = new GoogleAuth;
var client = new auth.OAuth2(GoogleUtils.clientIDs, '', '');
client.verifyIdToken(
token,
GoogleUtils.clientIDs,
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
function(e, login) {
if (e) {
return next(e, null);
}
var payload = login.getPayload();
return next(null, payload);
});
Thanks for your help. I can't seem to find any of this info in the documentation. Google's APIs are very poorly documented it seems.
Unfortunately, as noted, the current ID token payload does not say whether the photo is the default one (probably something we should add). If you need an access token to call Google's REST APIs (such as people.get) for more user data, then you need to obtain an OAuth auth code, and exchange it for access and refresh tokens, as documented at https://developers.google.com/identity/sign-in/ios/offline-access

How to access Twitter screenname, avatar when autopublish has been turned off

In Meteor, I believe ordinarily you can get the screenname of a twitter user after they've logged in with {{services.twitter.screenName}}.
However with autopublish turned off the only thing that seems to be available is {{currentUser.profile.name}} (which returns their 'full name' i.e. Kevin Rose, not krose).
How would I go about getting the screenname or avatar from a user that has logged in with Twitter, if autopublish has been removed?
You just need to set up a publish record on the server to determine what information you're going to send to the client, and then subscribe to it in a client-side startup function (or better still, iron-router).
Meteor.publish("userData", function () {
return Meteor.users.find({_id: this.userId},
{fields: {'services.twitter': 1}});
});
That will provide the services field for the logged in user in Meteor.user() once that client has subscribed to "userData" in addition to the fields that are automatically supplied.
You need to manually publish / subscribe your data. By default, only emails, username and profile fields are published for Meteor.users collection (see the docs). So you need to publish others:
Meteor.publish('userData', function() {
if(!this.userId) return null;
return Meteor.users.find(this.userId, {fields: {
services: 1,
...
}});
});
After that, subscribe to this channel on the client:
Deps.autorun(function() {
Meteor.subscribe('userData');
});

Getting user profile with google oauth2

I'm trying to get user profile information upon logging in with google-oauth2. User successfully logs in and i can get the access_token and can refresh the token when needed.
Though i could not manage to get any information about the user despite reading the docs and trying for hours.
From "Retrieving profiles" section of developers guide :
https://www.google.com/m8/feeds/profiles/domain/domainName/full
should be enough. i've tried with "gmail.com", "google.com", "gmail", "google", "orkut", "orkut.com" , myregisteredappsdomainname (and .com) as domainName. i've also tried it with
https://www.google.com/m8/feeds/profiles/domain/domainName/full?access_token=access_token_for_user
all i managed to get was 401 error, where it says "That’s an error.". Regarding 401 error, I've refreshed the token and tried again with new token, but kept getting 401s.
How can i get profile information and image address for user upon logging in?
The scope you're looking for is:
https://www.googleapis.com/oauth2/v1/userinfo
This has been already answered here
I was getting similar errors requesting profiles even after correctly defining the scope and getting access tokens etc.. The trick for me was to include the API version on my requests. See here for more info http://code.google.com/googleapps/domain/profiles/developers_guide.html#Versioning
Maybe little late yet could this be helpful to someone. Below is the working code I wrote to get gplus user profile
In HTML below markup will display goolge signIn button
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR GPLUS CLIENT ID"
data-cookiepolicy="single_host_origin"
data-scope="email">
</span>
</span>
Below is the java script
var access_token;
/**
* Called when the Google+ client library reports authorization status.
*/
function signinCallback(authResult) {
access_token = authResult.access_token;
gapi.client.load('plus', 'v1', function () {
gapi.client.plus.people.get({ userId: 'me' }).execute(printProfile);
});
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function printProfile(resp) {
if (resp.code != 403) {
console.log('name:' + access_token.givenname);
console.log('last name:' + access_token.lastname);
console.log('email:' + access_token.emails[0]);
console.log('gender:' + access_token.gender);
console.log('profile image url:' + access_token.image.url);
}
}
Please make sure that you load google api javascript asynchronously within the body tag as below
<script type="text/javascript">
(function () {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
To handle logout refer to the answer I provide in below link, you will need to store access_token in backend so that during logout call this to be used, in my case I have stored in session and getting through ajax call
gapi.auth.signOut(); not working I'm lost
Hey why don't you look at the code given at:
http://www.codeproject.com/KB/aspnet/OAuth4Client.aspx
It definitely helps you. The project is actually an oauth playground to send correct oauth header to correct endpoints.

Twitter O-Auth Callback url

I am having a problem with Twitter's oauth authentication and using a callback url.
I am coding in php and using the sample code referenced by the twitter wiki, http://github.com/abraham/twitteroauth
I got that code, and tried a simple test and it worked nicely. However I want to programatically specify the callback url, and the example did not support that.
So I quickly modified the getRequestToken() method to take in a parameter and now it looks like this:
function getRequestToken($params = array()) {
$r = $this->oAuthRequest($this->requestTokenURL(), $params);
$token = $this->oAuthParseResponse($r);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
and my call looks like this
$tok = $to->getRequestToken(array('oauth_callback' => 'http://127.0.0.1/twitter_prompt/index.php'));
This is the only change I made, and the redirect works like a charm, however I am getting an error when I then try and use my newly granted access to try and make a call. I get a "Could not authenticate you" error. Also the application never actually gets added to the users authorized connections.
Now I read the specs and I thought all I had to do was specify the parameter when getting the request token. Could someone a little more seasoned in oauth and twitter possibly give me a hand? Thank You
I think this is fixed by twitter by now or you might have missed to provide a default callback url in your application settings, which is required for dynamic callback url to work as mentioned by others above.
Any case, I got this working by passing the oath_callback parameter while retrieving the request token. I am using twitter-async PHP library and had to make a small tweak to make the library pass the callback url.
If you are using twitter-async, the change is below:
modified getRequestToken and getAuthenticateURL functions to take callback url as parameter
public function getRequestToken($callback_url = null)
{
$params = empty($callback_url) ? null : array('oauth_callback'=>$callback_url);
$resp = $this->httpRequest('GET', $this->requestTokenUrl, $params);
return new EpiOAuthResponse($resp);
}
public function getAuthenticateUrl($callback_url = null)
{
$token = $this->getRequestToken($callback_url);
return $this->authenticateUrl . '?oauth_token=' . $token->oauth_token;
}
And pass the callback url from your PHP code.
$twitterObj->getAuthenticateUrl('http://localhost/twitter/confirm.php');
#Ian, twitter now allows 127.0.0.1 and has made some other recent changes.
#jtymann, check my answer here and see if it helps
Twitter oauth_callback parameter being ignored!
GL
jingles
even me to was getting 401 error.. but its resolved..
during registering your application to twitter you need to give callback url...
like http://localhost:8080.
i have done this using java...
so my code is: String CallbackURL="http://localhost:8080/tweetproj/index.jsp";
provider.retrieveRequestToken(consumer,CallbackURL);
where tweetproj is my project name
and index.jsp is just one jsp page...
Hope this may helps u...
After the user authorizes the application on twitter.com and they return to your callback URL you have to exchange the request token for an access token.
Twitter does not honor the oauth_callback parameter and will only use the one specified in the registered application settings.
It also doesn't allow for 127.0.0.1 or localhost names in that callback, so I've setup http://dev.twipler.com which is setup for 127.0.0.1 in DNS so you can safely use;
http://dev.twipler.com/twitter_prompt/index.php

Resources