Class: Box::Authorization

Inherits:
Object
  • Object
show all
Defined in:
lib/box/authorization.rb

Class Method Summary collapse

Class Method Details

.authorize(config = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
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
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/box/authorization.rb', line 5

def self.authorize(config = {})
  username, password = config[:username], config[:password]
  raise "Unable to get auth tokens without username and password" unless username && password

  require 'mechanize'

  Box.log '... attempting to authorize with username and password'
  client_id, client_secret = config[:client_id], config[:client_secret]


  agent   = Mechanize::new
  session = Session.new(config)

  # Get the authorization URL from Box by specifying redirect URL
  # as the arbitrary but working Chase bank home page - this must match the address at Box
  # authorize_url = box_session.authorize_url('https://anywhere.airdye.com/oauth2callback')
  authorize_url = session.authorize_url(redirect_uri: 'https://www.chase.com')

  # process the first login screen
   = agent.get(authorize_url)

  # get the login form where you enter the username and password
            = .form_with(name: 'login_form')
  .    = username
  .password = password

  # submit the form and get the allow/deny page back
  allow_page = agent.submit()

  # find the form that allows consent
  consent_form = allow_page.form_with(name: 'consent_form')

  # now find the button that submits the allow page with consent
  accept_button = consent_form.button_with(name: 'consent_accept')

  # Submit the form to cause the redirection with authentication code
  redirpage = agent.submit(consent_form, accept_button)

  # Use the CGI module to get a hash of the variables (stuff after ?)
  # and then the authentication code is embedded in [" and "] so
  # strip those
  code_query = CGI::parse(redirpage.uri.query)['code'].to_s
  code = code_query[2,code_query.length-4]

  # get the box access token using the authentication code
  session.aquire_access_token(code)

  # print the tokens to show we have them
  p session.access_token
  p session.refresh_token

  Box::Session.on_token_refresh.call(session.access_token, session.refresh_token)

  # Create a new Box client based on the authenticated session
  # ap Box.client.root.items

  return session.oauth2_access_token
end