Class: Twimock::API::Intent::Sessions

Inherits:
OAuth
  • Object
show all
Defined in:
lib/twimock/api/intent/sessions.rb

Constant Summary collapse

METHOD =
"POST"
PATH =
"/intent/sessions"

Instance Method Summary collapse

Methods inherited from OAuth

#initialize

Constructor Details

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

Instance Method Details

#call(env) ⇒ Object



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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/twimock/api/intent/sessions.rb', line 16

def call(env)
  return super unless called?(env)
  begin
    request = Rack::Request.new(env)
    body = query_string_to_hash(request.body.read)
    @oauth_token       = body.oauth_token
    @username_or_email = body["session[username_or_email]"]
    @password          = body["session[password]"]

    if !validate_request_token(@oauth_token)
      raise Twimock::Errors::InvalidRequestToken.new
    elsif body.cancel
      raise Twimock::Errors::OAuthCancelled.new
    elsif !(user = Twimock::User.find_by_tiwtter_id_or_email(@username_or_email))
      raise Twimock::Errors::InvalidUsernameOrEmail.new 
    elsif @password.blank? || @password != user.password
      raise Twimock::Errors::InvalidPassword.new 
    end
    request_token = Twimock::RequestToken.find_by_string(@oauth_token)
    request_token.user_id = user.id
    request_token.save!

    uri = Addressable::URI.new
    uri.query_values = { oauth_token: request_token.string,
                         oauth_verifier: request_token.verifier }
    callback_url = Twimock::Config.callback_url + "?" + uri.query

    status = 302
    body   = ""
    header = { "Content-Length" => body.bytesize.to_s,
               "Location" => callback_url }
    [ status, header, [ body ] ]
  rescue Twimock::Errors::OAuthCancelled
    status = 303
    body   = ""
    header = { "Content-Length" => body.bytesize.to_s,
               "Location" => "/oauth/authorize?oauth_token=#{@oauth_token}&cancel=true" }
    [ status, header, [ body ] ]
  rescue Twimock::Errors::InvalidUsernameOrEmail, Twimock::Errors::InvalidPassword => @error
    response = unauthorized
    response[0] = 302
    response[1].merge!( {"Location" => "/oauth/authenticate?oauth_token=#{@oauth_token}" })
    response
  rescue Twimock::Errors::InvalidRequestToken => @error
    return unauthorized
  rescue => @error
    internal_server_error
  end
end