Commit 8ad3be515a4d268796a5c3fffb8f0fc5ce80621e
Merge pull request #64 from tjschuck/make_cost_globally_changeable_externally
Custom getter/setter for BCrypt::Engine.costAman Gupta committed on 5/4/2013, 12:36:44 AM
Parent: 2a84f0e01db71967573b42cc2e730d867c1ce555
Parent: 882ae87f715b87b4ff06ce9203ab0d2dfa780696
Files changed
lib/bcrypt.rb | changed |
spec/bcrypt/password_spec.rb | changed |
lib/bcrypt.rb | ||
---|---|---|
@@ -35,13 +35,18 @@ | ||
35 | 35 | private_class_method :__bc_salt |
36 | 36 | private_class_method :__bc_crypt |
37 | 37 | end |
38 | 38 | |
39 | - class << self | |
40 | - attr_accessor :cost | |
39 | + @cost = nil | |
40 | + | |
41 | + def self.cost | |
42 | + @cost || DEFAULT_COST | |
41 | 43 | end |
42 | - self.cost = DEFAULT_COST | |
43 | 44 | |
45 | + def self.cost=(cost) | |
46 | + @cost = cost | |
47 | + end | |
48 | + | |
44 | 49 | # Given a secret and a valid salt (see BCrypt::Engine.generate_salt) calculates |
45 | 50 | # a bcrypt() password hash. |
46 | 51 | def self.hash_secret(secret, salt, cost = nil) |
47 | 52 | if valid_secret?(secret) |
spec/bcrypt/password_spec.rb | ||
---|---|---|
@@ -54,10 +54,25 @@ | ||
54 | 54 | |
55 | 55 | specify "the cost should be set to the global value if set" do |
56 | 56 | BCrypt::Engine.cost = 5 |
57 | 57 | BCrypt::Password.create("hello").cost.should equal(5) |
58 | + # unset the global value to not affect other tests | |
59 | + BCrypt::Engine.cost = nil | |
58 | 60 | end |
59 | 61 | |
62 | + specify "the cost should be set to an overridden constant for backwards compatibility" do | |
63 | + # suppress "already initialized constant" warning | |
64 | + old_verbose, $VERBOSE = $VERBOSE, nil | |
65 | + old_default_cost = BCrypt::Engine::DEFAULT_COST | |
66 | + | |
67 | + BCrypt::Engine::DEFAULT_COST = 5 | |
68 | + BCrypt::Password.create("hello").cost.should equal(5) | |
69 | + | |
70 | + # reset default to not affect other tests | |
71 | + BCrypt::Engine::DEFAULT_COST = old_default_cost | |
72 | + $VERBOSE = old_verbose | |
73 | + end | |
74 | + | |
60 | 75 | specify "should read the version, cost, salt, and hash" do |
61 | 76 | password = BCrypt::Password.new(@hash) |
62 | 77 | password.version.should eql("2a") |
63 | 78 | password.cost.should equal(5) |
Built with git-ssb-web