Module: AtCoderFriends::Scraping::Authentication

Included in:
Agent
Defined in:
lib/at_coder_friends/scraping/authentication.rb

Overview

fetch pages and authenticates user at login page if needed

Constant Summary collapse

XPATH_USERNAME =
'//*[@id="navbar-collapse"]/ul[2]/li[2]/a'

Instance Method Summary collapse

Instance Method Details

#fetch_raw(url) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/at_coder_friends/scraping/authentication.rb', line 21

def fetch_raw(url)
  begin
    return agent.get(url)
  rescue Mechanize::ResponseCodeError => e
    raise e if username_link(e.page)
  end

  agent.get("#{common_url('login')}?continue=#{CGI.escape(url)}")
end

#fetch_with_auth(url) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/at_coder_friends/scraping/authentication.rb', line 13

def fetch_with_auth(url)
  page = fetch_raw(url)
  page.uri.path == '/login' && page = (page)
  page.uri.path == '/login' && (raise AppError, 'Authentication failed.')
  show_username(page)
  page
end

#post_login(page) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/at_coder_friends/scraping/authentication.rb', line 31

def (page)
  user, pass = read_auth
  form = page.forms[1]
  form.field_with(name: 'username').value = user
  form.field_with(name: 'password').value = pass
  form.submit
end

#read_authObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/at_coder_friends/scraping/authentication.rb', line 39

def read_auth
  user = ctx.config['user'].to_s
  if user.empty?
    print('enter username:')
    user = $stdin.gets.chomp
  end

  pass = ctx.config['password'].to_s
  if pass.empty?
    print("enter password for #{user}:")
    pass = $stdin.noecho(&:gets).chomp
    puts
  end
  [user, pass]
end

#show_username(page) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/at_coder_friends/scraping/authentication.rb', line 55

def show_username(page)
  username_bak = @username
  link = username_link(page)
  @username = (link ? link.text.strip : '-')
  return if @username == username_bak || @username == '-'

  puts "logged in as #{@username}"
end


64
65
66
67
# File 'lib/at_coder_friends/scraping/authentication.rb', line 64

def username_link(page)
  link = page.search(XPATH_USERNAME)[0]
  link && link[:href] == '#' && link
end