How should I store twitter token so users don'

2019-07-23 16:26发布

问题:

I'm developing twitter application so I'm using twitter_oauth gem to authorize. Here's the code which is very basic one. So, if a user goes to /login it will redirect user to twitter login, once he logged in and click authorize the app, the he will be redirected back to my website.


  begin
    callback = ENV['twitter_callback'] || "http://127.0.0.1:4567/login/success"
    request_token = @twitterClient.request_token(:oauth_callback => callback)
    MemcacheUtil::set("request_token_twitter", request_token, 3000)
    redirect request_token.authorize_url
  rescue Exception => e  
    puts e.message  
    puts e.backtrace.join("\n") 
    raise Exception.new("Something's wrong with twitter!")
  end

Here's what I would like to do. If user logged out and he wants to login again. Right now, if he clicks the login button he'll be redirected to twitter again to authorize the app. Is there anyway I could overcome this. I notice some site then even though I logged out and i click login again. It does something and logged me in without going to twitter site. How do I do that? Do they keep my token and secret in cookies?

for example: http://www.klout.com

回答1:

You need to have your own user model for your app, then link 3rd-party accounts. OpenSocial spec defines Account as (domain, userId, username) so that is likely a safe bet. You could store this in memcached as well, or have a different storage, and then store your key on the device or in cookie depending on if web app or native app. Don't store the token in cookie, store reference to your user and then perform a lookup on first request and perhaps store your own auth token in memcached for the "session".

simple MySQL tables for user:

CREATE TABLE IF NOT EXISTS user (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(48), ..., PRIMARY KEY (id));

CREATE TABLE IF NOT EXISTS user_accounts (id INT NOT NULL AUTO_INCREMENT, domain VARCHAR(64), user_id VARCHAR(32), username VARCHAR(32), status TINYINT(1), PRIMARY KEY (id));

OR

simple JSON object for user/accounts (store in memcached for example with your own key)

"user":{"id":yourId, "name":"Some Name", 
    "accounts":[{"domain":"twitter.com", "user_id":"sometoken", "username":"handle"}]
}

Hope that is helpful. Key is store your own users, then reference your key as cookie or on device during subsequent visits and perform your own lookup. For performance you won't want to look up every request so I'd suggest you use memcached to store session thereafter for that user.