Class: Twimock::API::OAuth::AccessToken

Inherits:
Twimock::API::OAuth show all
Defined in:
lib/twimock/api/oauth/access_token.rb

Overview

OAuth 1.1 で利用するAPI Access Token を取得する

Constant Summary collapse

METHOD =
"POST"
PATH =
"/oauth/access_token"
AUTHORIZATION_REGEXP =
/OAuth oauth_body_hash=\"(.*)\", oauth_consumer_key=\"(.*)\", oauth_nonce=\"(.*)\", oauth_signature=\"(.*)\", oauth_signature_method=\"(.*)\", oauth_timestamp=\"(.*)\", oauth_token=\"(.*)\", oauth_verifier=\"(.*)\", oauth_version=\"(.*)\"/

Instance Method Summary collapse

Methods inherited from Twimock::API::OAuth

#initialize

Constructor Details

This class inherits a constructor from Twimock::API::OAuth

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/twimock/api/oauth/access_token.rb', line 14

def call(env)
  return super unless called?(env)
  begin
    authorization_header = env["authorization"] || env["HTTP_AUTHORIZATION"]
    oauth = parse_authorization_header(authorization_header)
    consumer_key  = oauth.consumer_key
    request_token = oauth.token

    raise Twimock::Errors::InvalidConsumerKey.new if !validate_consumer_key(consumer_key)
    application = Twimock::Application.find_by_api_key(consumer_key)
    if !validate_request_token(request_token, application.id)
      raise Twimock::Errors::InvalidRequestToken.new 
    end
    request_token = Twimock::RequestToken.find_by_string(request_token)
    user = Twimock::User.find_by_id(request_token.user_id)
    access_tokens = Twimock::AccessToken.where(user_id: user.id)
    unless access_token = access_tokens.find{|at| at.application_id == application.id }
      access_token = user.generate_access_token(application.id)
    end
  rescue Twimock::Errors::InvalidConsumerKey, Twimock::Errors::InvalidRequestToken => @error
    return unauthorized
  rescue => @error
    return internal_server_error
  end

  status = "200 OK"
  params = {
    oauth_token:        access_token.string,
    oauth_token_secret: access_token.secret,
    user_id:            user.id,
    screen_name:        user.twitter_id
  }
  body   = params.inject([]){|a, (k, v)| a << "#{k}=#{v}"}.join('&')
  header = { "Content-Length" => body.bytesize.to_s }

  [ status, header, [ body ] ]
end