How do I get the firebase current user id (uid) in python? - python

I need to get the current user id.
In Javascript I use this to obtain the id
uid = firebase.auth().currentUser.uid // uid= ABO0Xc2E6KSDodEhenICkXF371x1
how do I get the uid in python
?

This is the code to retrieve the user id without login or signup.
auth.current_user['localId']

user = auth.sign_in_with_email_and_password(email,password)
print(user['localId'])
this will display the current firebase UID on output screen

You didn't mention a library, but all your other questions are using Pyrebase, so skimming over the documentation (which you should definitely be reading)...
# Get a reference to the auth service
auth = firebase.auth()
# Log the user in
user = auth.sign_in_with_email_and_password(email, password)
# Get the user's idToken
token = user['idToken']

Resurfacing an old question, but looking in to the documentation of Pyrebase here, I noticed that when you refresh the token, the userId is (compared to the other auth functions) retreived. So my solution is:
user = auth.sign_in_with_email_and_password("email", "pass")
user = auth.refresh(user['refreshToken'])
print(user['userId'])
EDIT:
I now see there is a 'localId' variable in the user object even before refreshing - as #Abdul indicated.

Related

Tweepy API: unable to get queries to return user_fields

I've got a python flask app whose job is to work with the Twitter V2.0 API. I got to using the Tweepy API in my app because I was having difficulty cold coding the 3 legged auth flow. Anyway, since I got that working, I'm now running into difficulties executing some basic queries, like get_me() and get_user()
This is my code:
client = tweepy.Client(
consumer_key=private.API_KEY,
consumer_secret=private.API_KEY_SECRET,
access_token=access_token,
access_token_secret=access_token_secret)
user = client.get_me(expansions='author_id', user_fields=['username','created_at','location'])
print(user)
return('success')
And this is invariably the error:
tweepy.errors.BadRequest: 400 Bad Request
The expansions query parameter value [author_id] is not one of [pinned_tweet_id]
Per the Twitter docs for this endpoint, this should certainly work...I fail to understand why I the 'pinned_tweet_id' expansion is the particular issue.
I'm left wondering if I'm missing something basic here or if Tweepy is just a POS and I should considering rolling my own queries like I originally intended.
Tweet Author ID
You may have read the Twitter Docs incorrectly as the expansions parameter value has only pinned_tweet_id, and the tweet fields parameter has the author_id value you're looking for. Here is a screenshot for better clarification:
The code would look like:
client = tweepy.Client(
consumer_key=private.API_KEY,
consumer_secret=private.API_KEY_SECRET,
access_token=access_token,
access_token_secret=access_token_secret)
user = client.get_me(tweet_fields=['author_id'], user_fields=[
'username', 'created_at', 'location'])
print(user)
return('success')
User ID
If you're looking for the user id then try omitting tweet_fields and add id in the user_fields also shown in the Twitter Docs.
The code would look like:
client = tweepy.Client(
consumer_key=private.API_KEY,
consumer_secret=private.API_KEY_SECRET,
access_token=access_token,
access_token_secret=access_token_secret)
user = client.get_me(user_fields=['id', 'username', 'created_at', 'location'])
print(user)
return('success')
You can obtain the user id with user.data.id.
The solution is to drop the 'expansions' kwag and leave 'user_fields' as is. I was further confused by the fact that printing the returned user object does not show the requested user_fields as part of the data attribute. You have to explicitly access them through the data attribute, as below.

Need a Python script for Slack to deactivate a user [duplicate]

I have tried multiple approaches to this. Tried first getting the user without any user id - this returns me just my user, then tried getting user with other id's and it also retrieves data correctly. However, I can't seem to be able to set user attribute 'deleted'. i'm using this python approach.
slack_client.api_call('users.profile.set', deleted=True, user='U36D86MNK')
However I get the error message of:
{u'error': u'invalid_user', u'ok': False}
Maybe someone has already done this? It says in documentation that it's a paid service mentioning this message under a user property:
This argument may only be specified by team admins on paid teams.
But shouldn't it give me a 'paid service' response in that case then?
The users.profile.set apparently does not work for for setting each and every property of a user.
To set the deleted property there is another API method called users.admin.setInactive. Its an undocumented method and it will only work on paid teams.
Note: This requires a legacy token and doesn't work with App tokens - these are only available on paid plans and new legacy tokens can't be created anymore
in python you can do the following:
import requests
def del_slack_user(user_id): # the user_id can be found under get_slack_users()
key = 'TOKEN KEY' #replace token key with your actual token key
payload = {'token': key, 'user': user_id}
response = requests.delete('https://slack.com/api/users.admin.setInactive', params=payload)
print(response.content)
def get_slack_users():
url = 'https://slack.com/api/users.list?token=ACCESSTOKEN&pretty=1'
response = requests.get(url=url)
response_data = response.json() # turns the query into a json object to search through`
You can use Slack's SCIM API to enable and disable a user. Note that, as with the undocumented API endpoint mentioned in other answers this requires a Plus/Enterprise account.

How to get instagram username from username ID without API in Python?

I'm trying to find a way to get instagram username from the username ID in Python.
What I found so far is this:
https://api.instagram.com/v1/users/[USER-ID]?access_token=[YOUR-ACCESS-TOKEN]
I have a token number, but it only works for users added to sandbox. For other users I receive the following error:
{"meta": {"code": 400, "error_type": "APINotFoundError", "error_message": "this user does not exist"}}
I'm searching a solution for hours with no luck so far.
Is there a way to arrive to the same result without using a token?
Thanks a lot!
In my case I am getting data from tagFeed so I have picture code. If you have picture code of any of user's post then you can get username like this
https://www.instagram.com/p/picCODE/?__a=1
example: https://www.instagram.com/p/BaGce-NlMg7/?__a=1
it will return a JSON with the owner - username
Point your browser to https://i.instagram.com/api/v1/users/USERID/info/ (replace USERID by the user id). It returns a JSON in which the field user.username is that user's username. With curl and jq installed, this shell oneliner will directly return the username:
curl -s https://i.instagram.com/api/v1/users/USERID/info/ | jq -r .user.username
Alternatively, the Instaloader package provides a convenient way to obtain a username given its ID, without using the official Instagram API.
import instaloader
L = instaloader.Instaloader()
profile = instaloader.Profile.from_id(L.context, ID)
print(profile.username)
It works by querying one of the profile's posts (for which only the profile's ID is required), obtaining that post's metadata (instagram.com/p/SHORTCODE) and then returning the owner.username value of that post.
No, unfortunately you can't. You need a token with public_content permissions, and for that, you need to have a live app (not in sandbox).

How can i show a simple instagram feed with the new api permissions

I am trying to set up a instagram plugin on django cms to show my recent images on a homepage by the username set in the plugin. It seems you can no longer simply get public content from instagram. This is the current method im using with my sandbox account.
user_request = requests.get("https://api.instagram.com/v1/users/search?q=" + str(instance.username) + "&access_token=" + settings.INSTAGRAM_ACCESS_TOKEN)
user_id = user_request.json().values()[1][0]["id"]
r = requests.get("https://api.instagram.com/v1/users/"+ user_id +"/media/recent/?access_token=" + settings.INSTAGRAM_ACCESS_TOKEN + "&count=" + str(instance.limit))
recent_media = r.json()
The code above gets the username from the plugin model and makes a get request to the instagram api to get that user (i've heard this method doesn't always show the correct user as its just searching and getting the first user from a list).
Is this the right way to work with the instagram api and python, I was going to use python-instagram but that is no longer supported. The only other way i can think of doing it is authenticating the user on the site and using their access token which seems silly for what i need it for.
EDIT:
Would removing the username field and adding access_token instead be a better method ? Then use "/users/self/media/recent" and rule out the query to search for a user by username.
Yes, the first results is not always the match, you have loop through all the search results and compare the username to your searched username, and then get id
Something like this:
var user_id = 0;
user_request.json().values()["data"].forEach(function(user){
if(user.username == str(instance.username)){
user_id = user["id"]
}
});
if(user_id){
// make api call
} else {
// user not found
}

Twython - How to associate multiple twitter accounts with one user

I want to allow registered users to add multiple twitter accounts. I followed twython-django example, and got a working version of one user - one twitter account. If the user tries to use twitter login again, follows same view again, I get this error: Invalid / expired Token.
I tried adding force_login=true to oauth/authorize and oauth/authenticate, removing 'request_token' from request.session dict, but i still get Invalid Token error during get_authentication_tokens().
How to properly associate multiple twitter accounts with the same user, using twython? What am I missing here?
Here is an a twython-django example: https://github.com/ryanmcgrath/twython-django/blob/master/twython_django_oauth/views.py
My view:
def twitter_login(request):
redirect_back_to_url = request.build_absolute_uri()
if 'request_token' not in request.session:
# request authorization tokens
t = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
callback_url=redirect_back_to_url)
# Request an authorization url to send the user to...
request_oauth_key = t.get_authentication_tokens()
# signing current session as one with twitter authentication
request.session['request_token'] = request_oauth_key
# redirecting the user to twitter authorization url for authentication
return HttpResponseRedirect(request_oauth_key['auth_url'])
else:
# user authenticated, receiving auth token
t2 = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
oauth_token=request.session['request_token'][
'oauth_token'],
oauth_token_secret=request.session['request_token'][
'oauth_token_secret'])
oauth_key = t2.get_authorized_tokens()
# save authorized tokens
# twitter oauth tokens dont expire
token = Token.objects.get_or_create(account_name=oauth_key['screen_name'],
token=oauth_key['oauth_token'],
secret=oauth_key['oauth_token_secret'])
user = request.user.get_profile()
user.twitter.add(token[0].id)
user.save()
logger.info('Successfully acquired twitter oauth token.')
return HttpResponseRedirect(reverse('profile'))
Update: possible solution
I changed my view to this:
def twitter_login(request):
redirect_back_to_url = request.build_absolute_uri()
if 'request_token' not in request.session:
# request authorization tokens
t = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
callback_url=redirect_back_to_url)
# Request an authorization url to send the user to...
request_oauth_key = t.get_authentication_tokens()
# signing current session as one with twitter authentication
request.session['request_token'] = request_oauth_key
# redirecting the user to twitter authorization url for authentication
return HttpResponseRedirect(request_oauth_key['auth_url'])
else:
# user authenticated, receiving auth token
t2 = Twython(twitter_token=settings.TWITTER_CONSUMER_KEY,
twitter_secret=settings.TWITTER_CONSUMER_SECRET,
oauth_token=request.session['request_token'][
'oauth_token'],
oauth_token_secret=request.session['request_token'][
'oauth_token_secret'])
oauth_key = t2.get_authorized_tokens()
if 'screen_name' not in oauth_key:
del request.session['request_token']
request.session.modified = True
return HttpResponseRedirect(reverse('twitter_login'))
# save authorized tokens
# twitter oauth tokens dont expire
token = Token.objects.get_or_create(account_name=oauth_key['screen_name'],
token=oauth_key['oauth_token'],
secret=oauth_key['oauth_token_secret'])
user = request.user.get_profile()
user.twitter.add(token[0].id)
user.save()
logger.info('Successfully acquired twitter oauth token.')
return HttpResponseRedirect(reverse('profile'))
And not sure yet if this had anything to do with it. I added after line 272 in twython.py request_args['force_login'] = True. But, as i said, i'm not sure if that had any impact, cos according to https://dev.twitter.com/docs/api/1/post/oauth/request_token force login is not one of the optional args.
Some voodoo this was. lol.
Tell me if its a total rubbish.
Mmm, I believe OP got it working/right, but just as a quick breakdown, twython-django isn't built to support multiple account associations (it's also not on Django 1.5, so be careful with that until it's updated~).
You'd need to do what OP did and set up a separate table for Tokens that match over to a User, and then handle which account they're currently using by pulling the appropriate tokens. OPs use of force_login also seems to have worked because, while it's not necessarily documented, I believe it still works (according to this thread, unless I'm misreading it - if I am, I would love to be corrected).
I don't expect this answer to be accepted as I'm not really solving anything, but if anyone else encounters this I'm hoping to leave something more clear-cut than the above notes. Hope that's alright!

Categories