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
- #fetch_raw(url) ⇒ Object
- #fetch_with_auth(url) ⇒ Object
- #post_login(page) ⇒ Object
- #read_auth ⇒ Object
- #show_username(page) ⇒ Object
- #username_link(page) ⇒ Object
Instance Method Details
#fetch_raw(url) ⇒ Object
21 22 23 24 25 26 27 28 29 30 |
# 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 unless e.response_code == '404' 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 = post_login(page) page.uri.path == '/login' && (raise AppError, 'Authentication failed.') show_username(page) page end |
#post_login(page) ⇒ Object
32 33 34 35 36 37 38 |
# File 'lib/at_coder_friends/scraping/authentication.rb', line 32 def post_login(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_auth ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/at_coder_friends/scraping/authentication.rb', line 40 def read_auth user = config['user'].to_s if user.empty? print('Enter username:') user = STDIN.gets.chomp end pass = 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
56 57 58 59 60 61 62 63 |
# File 'lib/at_coder_friends/scraping/authentication.rb', line 56 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 |
#username_link(page) ⇒ Object
65 66 67 68 |
# File 'lib/at_coder_friends/scraping/authentication.rb', line 65 def username_link(page) link = page.search(XPATH_USERNAME)[0] link && link[:href] == '#' && link end |