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!
Related
For my system, my users have their own unique ID (participant_id) that I've provided them.
I have a flask server that registers my users with Fitbit.
#app.route('/fitbit_authorize')
def homepage(): #probably need to send participant_id here
return 'Authenticate with fitbit' % FITBIT_AUTHORIZATION_URL
Fitbit sends a post request regarding the successfulness of my participant registration to the following where I get their user access/refresh tokens for oauth:
#app.route('/fitbit_callback')
def fitbit_callback():
error = request.args.get('error', '')
if error:
return "Error: " + error
state = request.args.get('state', '')
code = request.args.get('code')
token = fitbit_access.get_full_token(code)
I was wondering how can I retrieve the authorizer's original ID (participant_id) in the callback. Is there anyway for me to pass additional information in the fitbit authorization process or what would be the best way for me to retrieve their participant_id?
Good question.
Oauth2 allows for you to include state information in the authorization request---You can include the participant_id in the state parameter: https://dev.fitbit.com/build/reference/web-api/oauth2/
state: Provides any state that might be useful to your application
when the user is redirected back to your application. This parameter
will be added to the redirect URI exactly as your application
specifies. Fitbit strongly recommend including an anti-forgery token
in this parameter and confirming its value in the redirect to mitigate
against cross-site request forgery (CSRF).
In addition to providing the participant_id, you should provide an anti-forgery token to help fight CSRF.
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.
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.
I am using oAuth2WebServerFlow to get an oAuth access token and then retrieve a list of a user's contacts. I'm using web2py as the web framework.
flow = oauth2client.client.OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope='https://www.google.com/m8/feeds',
user_agent=USER_AGENT)
callback = 'http://127.0.0.1:8000/Test/searcher/oauth2callback'
authorise_url = flow.step1_get_authorize_url(callback)
session.flow = pickle.dumps(flow)
redirect(authorise_url)
With the redirect then being handled as follows
flow = pickle.loads(session.flow)
credentials = flow.step2_exchange(request.vars)
My question is how to change the OAuth2Credentials object returned above into an OAuth2AccessToken object, that I can then use to authorise a request to the contacts library with something like:
gc = gdata.contacts.client.ContactsClient(source="")
token.authorize(gc)
gc.GetContacts
I've tried various methods with no success, normally getting an oAuth2AccessTokenError message of "Invalid Grant". I'm thinking something like this may work but also think there must be a simpler way!
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='https://www.google.com/m8/feeds', user_agent=USER_AGENT)
token.redirect_uri = 'http://127.0.0.1:8000/Test/searcher/oauth2callback'
token.get_access_token(<<code to pass the access_token out of the Credentials object??>>)
Can anyone help with this?
I managed to get this working. It was pretty straightforward actually, I just stopped using the OAuth2WebServerFlow, which didn't seem to be adding much value anyway. So the new code looks like this:
token = gdata.gauth.OAuth2Token(client_id, client_secret, scope, ua)
session.token = pickle.dumps(token)
redirect(token.generate_authorize_url(redirect_uri='http://127.0.0.1:8000/Test/default/oauth2callback'))
Followed by
def oauth2callback():
token = pickle.loads(session.token)
token.redirect_uri='http://127.0.0.1:8000/Test/default/oauth2callback'
token.get_access_token(request.vars.code)
gc = gdata.contacts.client.ContactsClient(source='')
gc = token.authorize(gc)
feed = gc.GetContacts()
Hope this is helpful to someoone!
Assuming you have code for newer OAuth2.0 APIs setup correctly, you can get this working by creating a Token class that modifies headers that converts Credentials -> Token class.
OAUTH_LABEL='OAuth '
#Transforms OAuth2 credentials to OAuth2 token.
class OAuthCred2Token(object):
def __init__(self, token_string):
self.token_string = token_string
def modify_request(self, http_request):
http_request.headers['Authorization'] = '%s%s' % (OAUTH_LABEL,
self.token_string)
ModifyRequest = modify_request
You can test it as follows:
gc = gdata.contacts.client.ContactsClient(source='')
token = OAuthCred2Token(creds.access_token)
gc.auth_token = token
print gc.GetContacts()
Note that this code will not handle token refreshes, which code using credentials handles.
In my own application, it is acceptable to make a simple call using a service to refresh the credentials before making a call to get contacts.
Here is sample code that I'm working with.
def index(request):
flow = OAuth2WebServerFlow(
client_id='xyz.apps.googleusercontent.com',
client_secret='xyz',
scope='https://www.googleapis.com/auth/plus.me',
user_agent='sample/1.0')
callback = 'http://%s/oauth2callback' % request.META[ 'HTTP_HOST' ]
authorize_url = flow.step1_get_authorize_url(callback)
return HttpResponse(flow)
For some reason 'flow' is always set to " " or empty instead of a request token. I have searched for days on this issue.
Can anyone tell me why I can't get a request token from google using this method?
fyi: I know that I should be redirecting the user to the authorize url, but I want to see if flow is set before I do since Google will provide the authorize url even if a request token wasn't returned.
Before you can use OAuth 2.0, you must register your application using
the Google APIs Console. After you've registered, go to the API Access
tab and copy the "Client ID" and "Client secret" values, which you'll
need later.
http://code.google.com/p/google-api-python-client/wiki/OAuth2#Registering
If this answer actually helps with your problem then I must bid an R.I.P. to S.O.