dh_easy-login 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8e590beaf09bfb67942de1e279668f6437cbfe91d6fd650826c28d53deb4b377
4
+ data.tar.gz: b633bbf7192c8990dcec5007d059895380492b29ba00dcbefa15b5d9b7b22ebc
5
+ SHA512:
6
+ metadata.gz: d65f589e664679017d52c83b50fe3ed9ec020297a1246b5e22065e2f680ff6db5f874fcbd1ae8ccdec2ccd795224f3d281f72fb5c99e784c2e0b441de6cd529a
7
+ data.tar.gz: b164a763e32d5620d0be20b9f5cf7c86c8c133f8cfff691858931d79cb69ef1fd6568cd3a65ba438bd1834ca1bf2b3b08bd79c5bc47f134319a76fa1e03a1c10
@@ -0,0 +1,12 @@
1
+ /.byebug*
2
+ /.bundle/
3
+ /.yardoc
4
+ /_yardoc/
5
+ /coverage/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /certs/
10
+ /checksum/
11
+ /vendor/
12
+ /Gemfile.lock
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.4.2
7
+ before_install: gem install bundler -v 1.16.3
@@ -0,0 +1 @@
1
+ --no-private
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at perry@datahen.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in dh_easy-login.gemspec
6
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 DataHen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,387 @@
1
+ [![Documentation](http://img.shields.io/badge/docs-rdoc.info-blue.svg)](http://rubydoc.org/gems/dh_easy-login/frames)
2
+ [![Gem Version](https://badge.fury.io/rb/dh_easy-login.svg)](http://github.com/DataHenOfficial/dh_easy-login/releases)
3
+ [![License](http://img.shields.io/badge/license-MIT-yellowgreen.svg)](#license)
4
+
5
+ # DhEasy login module
6
+ ## Description
7
+
8
+ DhEasy login is part of DhEasy gem collection. It provides an easy way to handle login and session recovery, quite useful when scraping websites with login features and expiring sessions.
9
+
10
+ Install gem:
11
+ ```ruby
12
+ gem install 'dh_easy-login'
13
+ ```
14
+
15
+ Require gem:
16
+ ```ruby
17
+ require 'dh_easy/login'
18
+ ```
19
+
20
+ Code documentation can be found [here](http://rubydoc.org/gems/dh_easy-login/frames).
21
+
22
+ ## How to implement
23
+
24
+ ### Before you start
25
+
26
+ It is true that most user cases for `dh_easy-login` gem applies to websites with login pages and create sessions, so we will cover this scenario on our example.
27
+
28
+ Therefore, `dh_easy-login` gem is designed to handle **ANY** kind of session recovery, even those that doesn't requires a login form `POST` by just changing the flow from:
29
+
30
+ ```
31
+ login -> login_post -> restore
32
+ ```
33
+
34
+ To whatever you need like for example:
35
+
36
+ ```
37
+ home -> search_page -> restore
38
+ ```
39
+
40
+ Here are some user case examples that can be fixed by `dh_easy-login` gem:
41
+
42
+ * Websites that invalidate requests with fast expiring cookies created on first request.
43
+ * Websites that generates tokens on every search (either on cookies or query_params) that are required to fetch a detail page.
44
+ * Websites that expires session due inactivity.
45
+ * Websites that uses complex login flows.
46
+ * etc.
47
+
48
+ Feel confident to expirement with it until it fit all your needs.
49
+
50
+ ### Adding dh_easy-login to your project
51
+
52
+ Let's assume a simple project implementing `dh_easy` like the one described on [dh_easy README.md](https://github.com/DataHenOfficial/dh_easy/blob/master/README.md) that scrapers your website.
53
+
54
+ Now lets assume your website has a login page `https://example.com/login` with a session that expires before our sample project scrape job finish, causing all remaining webpages to respond `403` HTTP response code and fail... quite the problem isn't it? Well, not anymore, `dh_easy-login` gem to the rescue!
55
+
56
+ First, let's create our base module that will contain our session validation and recovery logic, for this example, we will call it `LoginEnable` :
57
+
58
+ ```ruby
59
+ # ./lib/login_enable.rb
60
+
61
+ module LoginEnable
62
+ include DhEasy::Login::Plugin::EnabledBehavior
63
+
64
+ # Hook to initialize login_flow configuration.
65
+ def initialize_hook_login_plugin_enabled_behavior opts = {}
66
+ opts = {app_config: DhEasy::Core::Config.new(opts)}.merge opts
67
+ @login_flow = DhEasy::Login::Flow.new opts
68
+ @cookie = nil
69
+ end
70
+
71
+ # Get cookie after applying response cookie.
72
+ # @return [String] Cookie string.
73
+ def cookie
74
+ return @cookie if @cookie.nil?
75
+
76
+ raw_cookie = page['response_cookie'] || page['response_headers']['Set-Cookie']
77
+ @cookie = DhEasy::Core::Helper::Cookie.update(page['headers']['Cookie'], raw_cookie)
78
+ @cookie
79
+ end
80
+
81
+ # Validates session.
82
+ # @return [Boolean] `true` when session is valid, else `false`.
83
+ def valid_session?
84
+ ['200', '404'].include? page['response_status_code'].to_s.strip
85
+ end
86
+
87
+ # Fix page session when session is invalid.
88
+ # @return [Boolean] `true` when session is valid, else `false`.
89
+ def fix_session
90
+ return true if valid_session?
91
+
92
+ login_flow.fix_session do
93
+ save_pages [{
94
+ 'url' => 'https://example.com/login',
95
+ 'page_type' => 'login',
96
+ 'priority' => 9,
97
+ 'freshness' => Time.now.iso8601,
98
+ 'cookie' => "stl=#{salt}",
99
+ 'headers' => {
100
+ # Add any extra header you need here
101
+ 'Cookie' => "stl=#{salt}"
102
+ }
103
+ }]
104
+ end
105
+
106
+ false
107
+ end
108
+ end
109
+ ```
110
+
111
+ Notice that our example `valid_session` method uses `200` and `404` HTTP response codes to validate that our session hasn't expired yet, therefore, **_this might not be the case for your website_**, so make sure to modify this method to fit your needs.
112
+
113
+ Our `fix_session` method will store any page with a failed session by creating an output so it can be restored later once we have the new active session cookie.
114
+
115
+ `fix_session` method will also mark the current session cookie as expired and **_enqueue a new `login` page with HIGH priority as long as another parser hasn't already did it to avoid duplicates_**.
116
+
117
+ `cookie` method will merge the request cookies with the response cookies, so we can be sure that the cookies are always updated when needed.
118
+
119
+ Next step is to create a simple parser that enqueue the `POST` of our login page:
120
+
121
+ ```ruby
122
+ # ./parsers/login.rb
123
+
124
+ module Parsers
125
+ class Login
126
+ include DhEasy::Core::Plugin::Parser
127
+ include LoginEnable
128
+
129
+ def parse
130
+ pages << {
131
+ 'url' => 'http://example.com/login',
132
+ 'page_type' => 'login_post',
133
+ 'priority' => 10,
134
+ 'method' => 'POST',
135
+ 'cookie' => cookie,
136
+ 'headers' => {
137
+ # Add any extra header you need here
138
+ 'Cookie' => cookie
139
+ }
140
+ }
141
+ end
142
+ end
143
+ end
144
+ ```
145
+
146
+ Now let's handle the login response, seed and restore any page with an expired session:
147
+
148
+ ```ruby
149
+ # ./parsers/login_post.rb
150
+
151
+ module Parsers
152
+ class LoginPost
153
+ include DhEasy::Core::Plugin::Parser
154
+ include LoginEnable
155
+
156
+ def seed!
157
+ return if login_flow.seeded?
158
+
159
+ Seeders::Seeder.new(context: context).seed do |new_page|
160
+ login_flow.fix_page! new_page
161
+ end
162
+
163
+ login_flow.seeded!
164
+ end
165
+
166
+ def parse
167
+ login_flow.update_config(
168
+ 'cookie' => get_cookie,
169
+ 'expired' => false
170
+ )
171
+
172
+ # Wait for any pending fetch to be hold
173
+ sleep 10
174
+
175
+ login_flow.restore_held_pages
176
+ seed!
177
+ end
178
+ end
179
+ end
180
+ ```
181
+
182
+ Notice something interesting? that's right, the seeding happens **AFTER** we got our new active session cookie, so the pages we seed includes the session cookie. We use `login_flow.fix_page!` method to add our latest active session cookie along some internal `page['vars']` (used to handle page recovery) to our seeded pages.
183
+
184
+ **IMPORTANT:** This example assumes that `login_post` pages will never fails, but you might need to add some extra validations to make sure the login attempt was successful before restoring your pages.
185
+
186
+ **_Note:_** This example assumes that all pages to be seeded requires an active session, so we will add it to all pages we seed, but this will likely not apply to all pages to be seeded in a real life scenario, so make sure to add it only to those pages that requires an active session.
187
+
188
+ So next step is to modify our seeder so it allow the cookie inclusion by adding a `block` param that will be used by our `Parsers::LoginPost#seed!` method:
189
+
190
+ ```ruby
191
+ # ./seeder/seeder.rb
192
+
193
+ module Seeder
194
+ class Seeder
195
+ include DhEasy::Core::Plugin::Seeder
196
+
197
+ def seed &block
198
+ new_page = {
199
+ 'url' => 'https://example.com/login.rb?query=food',
200
+ 'page_type' => 'search'
201
+ }
202
+ block.call(page) unless block.nil?
203
+ pages << new_page
204
+ end
205
+ end
206
+ end
207
+ ```
208
+
209
+ Now we will need to create a new seeder to seed login page:
210
+
211
+ ```ruby
212
+ # ./seeder/login.rb
213
+
214
+ module Seeder
215
+ class Login
216
+ include DhEasy::Core::Plugin::Seeder
217
+
218
+ def seed
219
+ pages << {
220
+ 'url' => 'https://example.com/login',
221
+ 'page_type' => 'login',
222
+ 'priority' => 9
223
+ }
224
+ end
225
+ end
226
+ end
227
+ ```
228
+
229
+ Now let's modify our `./config.yaml` to add our new page types on it, as well as let us parse failed fetched pages since our example assumes that website will return `403` HTTP response code when session has expired:
230
+
231
+ ```yaml
232
+ # ./config.yaml
233
+
234
+ parse_failed_pages: true
235
+
236
+ seeder:
237
+ file: ./router/seeder.rb
238
+ disabled: false
239
+
240
+ parsers:
241
+ - page_type: search
242
+ file: ./router/parser.rb
243
+ disabled: false
244
+ - page_type: product
245
+ file: ./router/parser.rb
246
+ disabled: false
247
+ - page_type: login
248
+ file: ./router/parser.rb
249
+ disabled: false
250
+ - page_type: login_post
251
+ file: ./router/parser.rb
252
+ disabled: false
253
+ ```
254
+
255
+ And don't forget to modify `./dh_easy.yaml` to add our new routes and change our seeder so login page can be seed first instead of our old seeder:
256
+
257
+ ```yaml
258
+ # ./dh_easy.yaml
259
+
260
+ router:
261
+ parser:
262
+ routes:
263
+ - page_type: search
264
+ class: Parsers::Search
265
+ - page_type: product
266
+ class: Parsers::Product
267
+ - page_type: login
268
+ class: Parsers::Login
269
+ - page_type: login_post
270
+ class: Parsers::LoginPost
271
+
272
+ seeder:
273
+ routes:
274
+ - class: Seeder::Login
275
+ ```
276
+
277
+ Now, let's will need to modify our routers as well since we modified our `dh_easy.yaml` routes and added new classes:
278
+
279
+ ```ruby
280
+ # ./router/seeder.rb
281
+
282
+ require 'dh_easy/router'
283
+ require './seeder/login'
284
+
285
+ DhEasy::Router::Seeder.new.route context: self
286
+ ```
287
+
288
+ ```ruby
289
+ # ./router/parser.rb
290
+
291
+ require 'cgi'
292
+ require 'dh_easy/router'
293
+ require 'dh_easy/login'
294
+ require './lib/login_enable'
295
+ require './seeder/seeder'
296
+ require './parsers/search'
297
+ require './parsers/product'
298
+ require './parsers/login'
299
+ require './parsers/login_post'
300
+
301
+ DhEasy::Router::Parser.new.route context: self
302
+ ```
303
+
304
+ Next, we need to include our `LoginEnable` module on every parser that requires session validation to fix any expired session request. To do this, we will be using our `LoginEnable#fix_session` function as the first thing to do on each parser's `parse` method:
305
+
306
+ ```ruby
307
+ # ./parsers/search.rb
308
+
309
+ module Parsers
310
+ class Search
311
+ include DhEasy::Core::Plugin::Parser
312
+ include LoginEnable
313
+
314
+ def parse
315
+ return unless fix_session
316
+
317
+ html = Nokogiri.HTML content
318
+ html.css('.name').each do |element|
319
+ name = element.text.strip
320
+ pages << {
321
+ 'url' => "https://example.com/product/#{CGI::escape name}",
322
+ 'page_type' => 'product',
323
+ 'vars' => {'name' => name}
324
+ }
325
+ end
326
+ end
327
+ end
328
+ end
329
+ ```
330
+
331
+ ```ruby
332
+ # ./parsers/product.rb
333
+
334
+ module Parsers
335
+ class Product
336
+ include DhEasy::Core::Plugin::Parser
337
+ include LoginEnable
338
+
339
+ def parse
340
+ return unless fix_session
341
+
342
+ html = Nokogiri.HTML content
343
+ description = html.css('.description').first.text.strip
344
+ outputs << {
345
+ '_collection' => 'product',
346
+ 'name' => page['vars']['name'],
347
+ 'description' => description
348
+ }
349
+ end
350
+ end
351
+ end
352
+ ```
353
+
354
+ **_Note:_** This example asumes that all pages requires an active session, so we will add it to all parsers, but this will likely not apply to all parsers in a real life scenario since not all web pages will require session, so make sure to add it to only the parsers that needs it.
355
+
356
+ Finally, we need to make sure that every page that requires an active session is enqueued within our latest active session cookie, so we need to use `login_flow.fix_page!` method on all pages to be enqueued that applies.
357
+
358
+ As for this example, we already add it to our search pages enqueued by our seeder, so the only place left to modify is `./parsers/search.rb` parser since it enqueues `product` pages:
359
+
360
+ ```ruby
361
+ # ./parsers/search.rb
362
+
363
+ module Parsers
364
+ class Search
365
+ include DhEasy::Core::Plugin::Parser
366
+ include LoginEnable
367
+
368
+ def parse
369
+ return unless fix_session
370
+
371
+ html = Nokogiri.HTML content
372
+ html.css('.name').each do |element|
373
+ name = element.text.strip
374
+ new_page = {
375
+ 'url' => "https://example.com/product/#{CGI::escape name}",
376
+ 'page_type' => 'product',
377
+ 'vars' => {'name' => name}
378
+ }
379
+ login_flow.fix_page! new_page
380
+ pages << new_page
381
+ end
382
+ end
383
+ end
384
+ end
385
+ ```
386
+
387
+ Hurray! Now you have implemented a fully functional login flow with auto recovery capabilities on your project.