だから私はついにdropbox-sdkを使ってすべてを書き終えました
コントローラ
class DropboxController < ApplicationController
def new
db_session = DropboxSession.new(MULTIAPI_CONFIG['dropbox']['appKey'], MULTIAPI_CONFIG['dropbox']['appSecret'])
begin
db_session.get_request_token
rescue DropboxError => e
render template: "multi_api/home/refresh"
end
session[:dp_request_db_session] = db_session.serialize
# OAuth Step 2: Send the user to the Dropbox website so they can authorize
# our app. After the user authorizes our app, Dropbox will redirect them
# to our 'dp_callback' endpoint.
auth_url = db_session.get_authorize_url url_for(:dp_callback)
redirect_to auth_url
end
def destroy
session.delete(:dp_authorized_db_session)
render :json => checkAuth
end
def isAuthenticated
render :json => checkAuth
end
def checkAuth
val = {'isAuthenticated' => false}
begin
unless not session[:dp_authorized_db_session]
dbsession = DropboxSession.deserialize(session[:dp_authorized_db_session])
client = DropboxClient.new(dbsession, MULTIAPI_CONFIG['dropbox']['accessType'])
val = {'isAuthenticated' => true}
end
rescue DropboxError => e
val = {'isAuthenticated' => false}
end
val
end
def callback
# Finish OAuth Step 2
ser = session[:dp_request_db_session]
unless ser
render template: "multi_api/home/refresh"
return
end
db_session = DropboxSession.deserialize(ser)
# OAuth Step 3: Get an access token from Dropbox.
begin
db_session.get_access_token
rescue DropboxError => e
render template: "multi_api/home/refresh"
return
end
session.delete(:dp_request_db_session)
session[:dp_authorized_db_session] = db_session.serialize
render template: "multi_api/home/refresh"
end
end
ルート
get 'dp/logout', :to => 'dropbox#destroy'
get 'dp/login', :to => 'dropbox#new'
get 'dp/callback', :to => 'dropbox#callback', :as => :dp_callback
get 'dp/isAuthenticated', :to => 'dropbox#isAuthenticated'
multi_api/home/refresh.html.erb
<script type="text/javascript">
function refreshParent()
{
window.opener.location.reload();
if (window.opener.progressWindow)
window.opener.progressWindow.close();
window.close();
}
refreshParent();
</script>
ドロップボックスをリクエストしています
dbsession = DropboxSession.deserialize(session[:dp_authorized_db_session])
@client = DropboxClient.new(dbsession, MULTIAPI_CONFIG['dropbox']['accessType'])
ユーザーを Dropbox に認証するときに新しいタブを開きます。これが完了すると、元のページが自動的に更新されてタブが閉じます (参照: multi_pi/home/refresh.html.erb
)。
これはすべてJavaScriptで行うため、ユーザーが正常に認証されたかどうかを知る必要があるため、またはに設定されたキーdp/isAuthenticated
を含むjson文字列を返すルートを提供しました。'isAuthenticated'
true
false
接続ユーザーはデータベースには保存されず、セッションにのみ保存されます。そのため、セッションが破棄されると、再認証する必要があります。それらをデータベースに保存する場合は、@smarx ソリューションを掘り下げる必要があります。omniauth を使用すると、はるかに簡単になります。
ruby dropbox-sdkだけに依存したい人のための例として、ここにコードを書きました。