How should I store twitter token so users don't have to go to twitter_oauth everytime?

南楼画角 提交于 2019-12-11 11:07:24

问题


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.



来源:https://stackoverflow.com/questions/11491674/how-should-i-store-twitter-token-so-users-dont-have-to-go-to-twitter-oauth-ever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!