From 77ee60b53d5c0502c85b9be3fa196b657cf8861f Mon Sep 17 00:00:00 2001 From: i2bskn Date: Tue, 18 Nov 2014 01:04:45 +0900 Subject: [PATCH 01/14] Refactoring --- LICENSE.txt | 3 +- lib/passwd.rb | 5 +++ lib/passwd/active_record.rb | 62 +++++++++++++++---------------- lib/passwd/base.rb | 41 ++++++-------------- lib/passwd/errors.rb | 15 ++------ lib/passwd/password.rb | 2 +- passwd.gemspec | 3 +- spec/passwd/active_record_spec.rb | 10 ++--- 8 files changed, 60 insertions(+), 81 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index be47849..737eabd 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2013 i2bskn +Copyright (c) 2013-2014 i2bskn MIT License @@ -20,3 +20,4 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/lib/passwd.rb b/lib/passwd.rb index 610ab19..e7e9bec 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -1,3 +1,4 @@ +require "singleton" require "digest/sha1" require "digest/sha2" @@ -7,3 +8,7 @@ require "passwd/password" require "passwd/active_record" +module Passwd + extend Base +end + diff --git a/lib/passwd/active_record.rb b/lib/passwd/active_record.rb index acbe20d..0c1c9b6 100644 --- a/lib/passwd/active_record.rb +++ b/lib/passwd/active_record.rb @@ -1,7 +1,7 @@ module Passwd module ActiveRecord module ClassMethods - def define_column(options={}) + def define_column(options = {}) id_name = options.fetch(:id, :email) salt_name = options.fetch(:salt, :salt) password_name = options.fetch(:password, :password) @@ -13,48 +13,46 @@ def define_column(options={}) end private - def define_singleton_auth(id_name, salt_name, password_name) - define_singleton_method :authenticate do |id, pass| - user = self.where(id_name => id).first - user if user && Passwd.auth(pass, user.send(salt_name), user.send(password_name)) + def define_singleton_auth(id_name, salt_name, password_name) + define_singleton_method :authenticate do |id, pass| + user = self.find_by(id_name => id) + user && Passwd.auth(pass, user.send(salt_name), user.send(password_name)) ? user : nil + end end - end - def define_instance_auth(id_name, salt_name, password_name) - define_method :authenticate do |pass| - Passwd.auth(pass, self.send(salt_name), self.send(password_name)) + def define_instance_auth(id_name, salt_name, password_name) + define_method :authenticate do |pass| + Passwd.auth(pass, self.send(salt_name), self.send(password_name)) + end end - end - def define_set_password(id_name, salt_name, password_name) - define_method :set_password do |pass=nil| - password = pass || Passwd.create - salt = self.send(salt_name) || Passwd.hashing("#{self.send(id_name)}#{Time.now.to_s}") - self.send("#{salt_name.to_s}=", salt) - self.send("#{password_name.to_s}=", Passwd.hashing("#{salt}#{password}")) - password + def define_set_password(id_name, salt_name, password_name) + define_method :set_password do |pass=nil| + password = pass || Passwd.create + salt = self.send(salt_name) || Passwd.hashing("#{self.send(id_name)}#{Time.now.to_s}") + self.send("#{salt_name.to_s}=", salt) + self.send("#{password_name.to_s}=", Passwd.hashing("#{salt}#{password}")) + password + end end - end - def define_update_password(salt_name, password_name) - define_method :update_password do |old_pass, new_pass, policy_check=false| - if Passwd.auth(old_pass, self.send(salt_name), self.send(password_name)) - if policy_check - raise Passwd::PolicyNotMatch, "Policy not match" unless Passwd.policy_check(new_pass) - end + def define_update_password(salt_name, password_name) + define_method :update_password do |old_pass, new_pass, policy_check = false| + if Passwd.auth(old_pass, self.send(salt_name), self.send(password_name)) + if policy_check + raise Passwd::PolicyNotMatch, "Policy not match" unless Passwd.policy_check(new_pass) + end - set_password(new_pass) - else - raise Passwd::AuthError + set_password(new_pass) + else + raise Passwd::AuthError + end end end - end end - class << self - def included(base) - base.extend ClassMethods - end + def self.included(base) + base.extend ClassMethods end end end diff --git a/lib/passwd/base.rb b/lib/passwd/base.rb index 2a0fe83..016b65e 100644 --- a/lib/passwd/base.rb +++ b/lib/passwd/base.rb @@ -1,4 +1,3 @@ -require "singleton" require "passwd/configuration/config" require "passwd/configuration/tmp_config" require "passwd/configuration/policy" @@ -8,53 +7,37 @@ module Passwd @policy = Policy.instance module Base - def create(options={}) - if options.empty? - config = @config - else - config = TmpConfig.new(@config, options) - end + def create(options = {}) + config = options.empty? ? @config : TmpConfig.new(@config, options) Array.new(config.length){config.letters[rand(config.letters.size)]}.join end def auth(password_text, salt_hash, password_hash) - enc_pass = Passwd.hashing("#{salt_hash}#{password_text}") - password_hash == enc_pass + password_hash == hashing("#{salt_hash}#{password_text}") end - def hashing(plain, algorithm=nil) - if algorithm.nil? - eval "Digest::#{@config.algorithm.to_s.upcase}.hexdigest \"#{plain}\"" - else - eval "Digest::#{algorithm.to_s.upcase}.hexdigest \"#{plain}\"" - end + def hashing(plain, algorithm = nil) + algorithm = algorithm ? algorithm.to_s.upcase : @config.algorithm.to_s.upcase + Digest.const_get(algorithm).hexdigest plain end - def confirm_check(password, confirm, with_policy=false) + def confirm_check(password, confirm, with_policy = false) raise PasswordNotMatch, "Password not match" if password != confirm return true unless with_policy - Passwd.policy_check(password) + policy_check(password) end - def configure(options={}, &block) + def configure(options = {}, &block) if block_given? @config.configure &block else - if options.empty? - @config - else - @config.merge options - end + options.empty? ? @config : @config.merge(options) end end alias :config :configure def policy_configure(&block) - if block_given? - @policy.configure &block - else - @policy - end + block_given? ? @policy.configure(&block) : @policy end def policy_check(password) @@ -69,7 +52,5 @@ def reset_policy @policy.reset end end - - extend Base end diff --git a/lib/passwd/errors.rb b/lib/passwd/errors.rb index bb8b7da..7079c44 100644 --- a/lib/passwd/errors.rb +++ b/lib/passwd/errors.rb @@ -1,14 +1,7 @@ module Passwd - class PasswdError < StandardError - end - - class AuthError < PasswdError - end - - class PasswordNotMatch < PasswdError - end - - class PolicyNotMatch < PasswdError - end + class PasswdError < StandardError; end + class AuthError < PasswdError; end + class PasswordNotMatch < PasswdError; end + class PolicyNotMatch < PasswdError; end end diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index e62008d..4bb8073 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -2,7 +2,7 @@ module Passwd class Password attr_reader :text, :hash, :salt_text, :salt_hash - def initialize(options={}) + def initialize(options = {}) @text = options.fetch(:password, Passwd.create) @salt_text = options.fetch(:salt_text, Time.now.to_s) @salt_hash = Passwd.hashing(@salt_text) diff --git a/passwd.gemspec b/passwd.gemspec index 36191f9..9a845a8 100644 --- a/passwd.gemspec +++ b/passwd.gemspec @@ -17,9 +17,10 @@ Gem::Specification.new do |spec| spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] - spec.add_development_dependency "bundler", "~> 1.3" + spec.add_development_dependency "bundler" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "coveralls" spec.add_development_dependency "simplecov" end + diff --git a/spec/passwd/active_record_spec.rb b/spec/passwd/active_record_spec.rb index 135f0be..bc74017 100644 --- a/spec/passwd/active_record_spec.rb +++ b/spec/passwd/active_record_spec.rb @@ -43,23 +43,23 @@ class User let!(:record) { record = double("record mock") allow(record).to receive_messages(salt: salt, password: password_hash) - response = [record] - allow(User).to receive(:where) {response} + response = record + allow(User).to receive(:find_by) {response} record } it "user should be returned if authentication is successful" do - expect(User).to receive(:where) + expect(User).to receive(:find_by) expect(User.authenticate("valid_id", password_text)).to eq(record) end it "should return nil if authentication failed" do - expect(User).to receive(:where) + expect(User).to receive(:find_by) expect(User.authenticate("valid_id", "invalid_secret")).to be_nil end it "should return nil if user not found" do - expect(User).to receive(:where).with(email: "invalid_id") {[]} + expect(User).to receive(:find_by).with(email: "invalid_id") {nil} expect(User.authenticate("invalid_id", password_text)).to be_nil end end From 2c8901c140d87145594d22fbf51b907223dbad7b Mon Sep 17 00:00:00 2001 From: i2bskn Date: Wed, 19 Nov 2014 02:42:06 +0900 Subject: [PATCH 02/14] while refactoring --- .travis.yml | 3 ++ lib/passwd.rb | 5 +- lib/passwd/active_record.rb | 59 --------------------- lib/passwd/base.rb | 53 ++---------------- lib/passwd/configuration.rb | 59 +++++++++++++++++++++ lib/passwd/configuration/abstract_config.rb | 36 ------------- lib/passwd/configuration/config.rb | 23 -------- lib/passwd/configuration/policy.rb | 45 ---------------- lib/passwd/configuration/tmp_config.rb | 17 ------ lib/passwd/hashlib.rb | 13 +++++ lib/passwd/password.rb | 40 ++++---------- lib/passwd/salt.rb | 40 ++++++++++++++ 12 files changed, 130 insertions(+), 263 deletions(-) delete mode 100644 lib/passwd/active_record.rb create mode 100644 lib/passwd/configuration.rb delete mode 100644 lib/passwd/configuration/abstract_config.rb delete mode 100644 lib/passwd/configuration/config.rb delete mode 100644 lib/passwd/configuration/policy.rb delete mode 100644 lib/passwd/configuration/tmp_config.rb create mode 100644 lib/passwd/hashlib.rb create mode 100644 lib/passwd/salt.rb diff --git a/.travis.yml b/.travis.yml index 03e783e..a22b46b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,9 @@ language: ruby rvm: - 2.0.0 - 2.1.0 +branches: + only: + - master gemfile: - Gemfile script: bundle exec rake spec diff --git a/lib/passwd.rb b/lib/passwd.rb index e7e9bec..8f4382f 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -1,12 +1,13 @@ -require "singleton" require "digest/sha1" require "digest/sha2" require "passwd/version" require "passwd/errors" +require "passwd/configuration" +require "passwd/hashlib" require "passwd/base" +require "passwd/salt" require "passwd/password" -require "passwd/active_record" module Passwd extend Base diff --git a/lib/passwd/active_record.rb b/lib/passwd/active_record.rb deleted file mode 100644 index 0c1c9b6..0000000 --- a/lib/passwd/active_record.rb +++ /dev/null @@ -1,59 +0,0 @@ -module Passwd - module ActiveRecord - module ClassMethods - def define_column(options = {}) - id_name = options.fetch(:id, :email) - salt_name = options.fetch(:salt, :salt) - password_name = options.fetch(:password, :password) - - define_singleton_auth(id_name, salt_name, password_name) - define_instance_auth(id_name, salt_name, password_name) - define_set_password(id_name, salt_name, password_name) - define_update_password(salt_name, password_name) - end - - private - def define_singleton_auth(id_name, salt_name, password_name) - define_singleton_method :authenticate do |id, pass| - user = self.find_by(id_name => id) - user && Passwd.auth(pass, user.send(salt_name), user.send(password_name)) ? user : nil - end - end - - def define_instance_auth(id_name, salt_name, password_name) - define_method :authenticate do |pass| - Passwd.auth(pass, self.send(salt_name), self.send(password_name)) - end - end - - def define_set_password(id_name, salt_name, password_name) - define_method :set_password do |pass=nil| - password = pass || Passwd.create - salt = self.send(salt_name) || Passwd.hashing("#{self.send(id_name)}#{Time.now.to_s}") - self.send("#{salt_name.to_s}=", salt) - self.send("#{password_name.to_s}=", Passwd.hashing("#{salt}#{password}")) - password - end - end - - def define_update_password(salt_name, password_name) - define_method :update_password do |old_pass, new_pass, policy_check = false| - if Passwd.auth(old_pass, self.send(salt_name), self.send(password_name)) - if policy_check - raise Passwd::PolicyNotMatch, "Policy not match" unless Passwd.policy_check(new_pass) - end - - set_password(new_pass) - else - raise Passwd::AuthError - end - end - end - end - - def self.included(base) - base.extend ClassMethods - end - end -end - diff --git a/lib/passwd/base.rb b/lib/passwd/base.rb index 016b65e..56c86c8 100644 --- a/lib/passwd/base.rb +++ b/lib/passwd/base.rb @@ -1,55 +1,8 @@ -require "passwd/configuration/config" -require "passwd/configuration/tmp_config" -require "passwd/configuration/policy" - module Passwd - @config = Config.instance - @policy = Policy.instance - module Base - def create(options = {}) - config = options.empty? ? @config : TmpConfig.new(@config, options) - Array.new(config.length){config.letters[rand(config.letters.size)]}.join - end - - def auth(password_text, salt_hash, password_hash) - password_hash == hashing("#{salt_hash}#{password_text}") - end - - def hashing(plain, algorithm = nil) - algorithm = algorithm ? algorithm.to_s.upcase : @config.algorithm.to_s.upcase - Digest.const_get(algorithm).hexdigest plain - end - - def confirm_check(password, confirm, with_policy = false) - raise PasswordNotMatch, "Password not match" if password != confirm - return true unless with_policy - policy_check(password) - end - - def configure(options = {}, &block) - if block_given? - @config.configure &block - else - options.empty? ? @config : @config.merge(options) - end - end - alias :config :configure - - def policy_configure(&block) - block_given? ? @policy.configure(&block) : @policy - end - - def policy_check(password) - @policy.valid?(password, @config) - end - - def reset_config - @config.reset - end - - def reset_policy - @policy.reset + def random(options = {}) + c = Config.to_options.merge(options) + Array.new(c[:length]){c[:letters][rand(c[:letters].size)]}.join end end end diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb new file mode 100644 index 0000000..42a5d5c --- /dev/null +++ b/lib/passwd/configuration.rb @@ -0,0 +1,59 @@ +module Passwd + class Configuration + KINDS = %i(lower upper number).freeze + LETTERS = KINDS.map {|k| "letters_#{k}".to_sym}.freeze + + VALID_OPTIONS = [ + :algorithm, + :length, + ].concat(KINDS).concat(LETTERS).freeze + + attr_accessor *VALID_OPTIONS + + def initialize + reset + end + + def configure + yield self + end + + KINDS.each do |kind| + define_method "#{kind}_chars" do + self.send("letters_#{kind}") || [] + end + end + + def letters + KINDS.detect {|k| self.send(k)} || (raise "letters is empty") + LETTERS.map {|l| self.send(l)}.flatten + end + + def to_options + { + length: self.length, + letters: self.letters + } + end + + def reset + self.algorithm = :sha512 + self.length = 8 + self.lower = true + self.upper = true + self.number = true + self.letters_lower = ("a".."z").to_a + self.letters_upper = ("A".."Z").to_a + self.letters_number = ("0".."9").to_a + end + + module Accessible + def self.included(base) + base.const_set(:Config, Configuration.new) + end + end + end + + include Configuration::Accessible +end + diff --git a/lib/passwd/configuration/abstract_config.rb b/lib/passwd/configuration/abstract_config.rb deleted file mode 100644 index 8233e78..0000000 --- a/lib/passwd/configuration/abstract_config.rb +++ /dev/null @@ -1,36 +0,0 @@ -module Passwd - class AbstractConfig - VALID_OPTIONS_KEYS = [ - :algorithm, - :length, - :lower, - :upper, - :number, - :letters_lower, - :letters_upper, - :letters_number - ].freeze - - attr_accessor *VALID_OPTIONS_KEYS - - def configure - yield self - end - - def merge(configs) - configs.keys.each do |k| - send("#{k}=", configs[k]) - end - end - - def letters - chars = [] - chars.concat(self.letters_lower) if self.lower - chars.concat(self.letters_upper) if self.upper - chars.concat(self.letters_number) if self.number - raise "letters is empty" if chars.empty? - chars - end - end -end - diff --git a/lib/passwd/configuration/config.rb b/lib/passwd/configuration/config.rb deleted file mode 100644 index b04a87b..0000000 --- a/lib/passwd/configuration/config.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "passwd/configuration/abstract_config" - -module Passwd - class Config < AbstractConfig - include Singleton - - def initialize - reset - end - - def reset - self.algorithm = :sha512 - self.length = 8 - self.lower = true - self.upper = true - self.number = true - self.letters_lower = ("a".."z").to_a - self.letters_upper = ("A".."Z").to_a - self.letters_number = ("0".."9").to_a - end - end -end - diff --git a/lib/passwd/configuration/policy.rb b/lib/passwd/configuration/policy.rb deleted file mode 100644 index 8e1472d..0000000 --- a/lib/passwd/configuration/policy.rb +++ /dev/null @@ -1,45 +0,0 @@ -module Passwd - class Policy - include Singleton - - VALID_OPTIONS_KEYS = [ - :min_length, - :require_lower, - :require_upper, - :require_number - ].freeze - - attr_accessor *VALID_OPTIONS_KEYS - - def initialize - reset - end - - def configure - yield self - end - - def valid?(password, config) - return false if self.min_length > password.size - return false if self.require_lower && !include_char?(config.letters_lower, password) - return false if self.require_upper && !include_char?(config.letters_upper, password) - return false if self.require_number && !include_char?(config.letters_number, password) - true - end - - def include_char?(letters, strings) - strings.each_char do |c| - return true if letters.include? c - end - false - end - - def reset - self.min_length = 8 - self.require_lower = true - self.require_upper = false - self.require_number = true - end - end -end - diff --git a/lib/passwd/configuration/tmp_config.rb b/lib/passwd/configuration/tmp_config.rb deleted file mode 100644 index 0031566..0000000 --- a/lib/passwd/configuration/tmp_config.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "passwd/configuration/abstract_config" - -module Passwd - class TmpConfig < AbstractConfig - def initialize(config, options) - config.instance_variables.each do |v| - key = v.to_s.sub(/^@/, "").to_sym - if options.has_key? key - instance_variable_set v, options[key] - else - instance_variable_set v, config.instance_variable_get(v) - end - end - end - end -end - diff --git a/lib/passwd/hashlib.rb b/lib/passwd/hashlib.rb new file mode 100644 index 0000000..d583532 --- /dev/null +++ b/lib/passwd/hashlib.rb @@ -0,0 +1,13 @@ +module Passwd + module Hashlib + def digest(plain, _algorithm = nil) + algorithm(_algorithm || Config.algorithm).hexdigest(plain) + end + + private + def algorithm(_algorithm) + Digest.const_get(_algorithm.upcase, false) + end + end +end + diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index 4bb8073..28beb30 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -1,40 +1,18 @@ module Passwd class Password - attr_reader :text, :hash, :salt_text, :salt_hash + include Base + include Hashlib - def initialize(options = {}) - @text = options.fetch(:password, Passwd.create) - @salt_text = options.fetch(:salt_text, Time.now.to_s) - @salt_hash = Passwd.hashing(@salt_text) - @hash = Passwd.hashing("#{@salt_hash}#{@text}") - end - - def text=(password) - @hash = Passwd.hashing("#{@salt_hash}#{password}") - @text = password - end - - def hash=(password_hash) - @text = nil - @hash = password_hash - end - - def salt_text=(salt_text) - @salt_hash = Passwd.hashing(salt_text) - @hash = Passwd.hashing("#{@salt_hash}#{@text}") - @salt_text = salt_text - end + attr_accessor :salt + attr_reader :plain, :hash - def salt_hash=(salt_hash) - @salt_text = nil - @hash = Passwd.hashing("#{salt_hash}#{@text}") - @salt_hash = salt_hash + def initialize(options = {}) end - def ==(password) - enc_pass = Passwd.hashing("#{@salt_hash}#{password}") - @hash == enc_pass - end + private + def default_options + {} + end end end diff --git a/lib/passwd/salt.rb b/lib/passwd/salt.rb new file mode 100644 index 0000000..c028788 --- /dev/null +++ b/lib/passwd/salt.rb @@ -0,0 +1,40 @@ +module Passwd + class Salt + include Hashlib + + attr_reader :plain, :hash + + def initialize(options = {}) + options.merge! default_options + if options.has_key?(:hash) + self.hash = options[:hash] + else + self.plain = options[:plain] || (raise ArgumentError) + end + end + + def plain=(value) + @plain = value + @hash = digest(value) + end + + def hash=(value) + @plain = nil + @hash = value + end + + def self.from_plain(value) + new(plain: value) + end + + def self.from_hash(value) + new(hash: value) + end + + private + def default_options + {plain: Time.now.to_s} + end + end +end + From 4ee97df3afb36f29dec9c44469978ead17123fa8 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Thu, 20 Nov 2014 02:27:13 +0900 Subject: [PATCH 03/14] remake lib --- lib/passwd.rb | 78 +++++++++++++++++++++++++++++++++++- lib/passwd/base.rb | 26 +++++++++++- lib/passwd/configuration.rb | 35 +++++++++++----- lib/passwd/hashlib.rb | 13 ------ lib/passwd/password.rb | 79 +++++++++++++++++++++++++++++++++++-- lib/passwd/policy.rb | 28 +++++++++++++ lib/passwd/salt.rb | 28 ++++++++----- 7 files changed, 249 insertions(+), 38 deletions(-) delete mode 100644 lib/passwd/hashlib.rb create mode 100644 lib/passwd/policy.rb diff --git a/lib/passwd.rb b/lib/passwd.rb index 8f4382f..fcd0bbc 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -3,13 +3,89 @@ require "passwd/version" require "passwd/errors" +require "passwd/policy" require "passwd/configuration" -require "passwd/hashlib" require "passwd/base" require "passwd/salt" require "passwd/password" +require "passwd/rails/railtie" +require "passwd/rails/active_record" module Passwd + include Configuration::Accessible + extend Configuration::Writable extend Base + + def self.policy_check(plain) + Password.from_plain(plain).valid? + end + + def self.match?(plain, salt_hash, hash) + Password.from_hash(hash, salt_hash).match?(plain) + end +end + +if defined?(ActiveRecord) + class ActiveRecord::Base + def self.with_authenticate(options = {}) + id_name = options.fetch(:id, :email) + salt_name = options.fetch(:salt, :salt) + password_name = options.fetch(:password, :password) + + _define_to_password(salt_name, password_name) + _define_singleton_auth(id_name) + _define_instance_auth + _define_set_password(id_name, salt_name, password_name) + _define_update_password(salt_name, password_name) + end + + private + def _define_to_password(salt_name, password_name) + define_method :to_password do + _salt_hash = self.send(salt_name) + _password = self.send(password_name) + Passwd::Password.from_hash(_password, _salt_hash)) + end + end + + def _define_singleton_auth(id_name) + define_singleton_method :authenticate do |_id, _pass| + user = self.find_by(id_name => _id) + user if user && user.to_password.match?(_pass) + end + end + + def _define_instance_auth + define_method :authenticate do |_pass| + self.to_password.match?(_pass) + end + end + + def _define_set_password(id_name, salt_name, password_name) + define_method :set_password do |_pass = nil| + _password = _pass || Passwd.random + _salt = self.send(salt_name) || Passwd::Salt. + _salt ||= Passwd.digest_without_stretching("#{self.send(id_name)}#{Time.now.to_s}") + self.send("#{salt_name}=", _salt) + self.send("#{password_name}=", Passwd.digest_without_stretching("#{_salt}#{_password}")) + _password + end + end + + def _define_update_password(salt_name, password_name) + define_method :update_password do |_old_pass, _new_pass, _policy = false| + _pass = self.to_password + if _pass.match?(_old_pass) + if _policy + raise unless Passwd.policy_check(_new_pass) + end + + self.set_password(_new_pass) + else + raise + end + end + end + end end diff --git a/lib/passwd/base.rb b/lib/passwd/base.rb index 56c86c8..82e7be5 100644 --- a/lib/passwd/base.rb +++ b/lib/passwd/base.rb @@ -1,9 +1,31 @@ module Passwd module Base def random(options = {}) - c = Config.to_options.merge(options) - Array.new(c[:length]){c[:letters][rand(c[:letters].size)]}.join + c = Config.merge(options) + Array.new(c.length){c.letters[rand(c.letters.size)]}.join end + + def digest(plain, _algorithm = nil) + _algorithm ||= Config.algorithm + + if Config.stretching + _pass = plain + Config.stretching.times do + _pass = digest_without_stretching(_pass, _algorithm) + end + else + digest_without_stretching(plain, _algorithm) + end + end + + def digest_without_stretching(plain, _algorithm = nil) + algorithm(_algorithm || Config.algorithm).hexdigest(plain) + end + + private + def algorithm(_algorithm) + Digest.const_get(_algorithm.upcase, false) + end end end diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb index 42a5d5c..eba9302 100644 --- a/lib/passwd/configuration.rb +++ b/lib/passwd/configuration.rb @@ -6,6 +6,8 @@ class Configuration VALID_OPTIONS = [ :algorithm, :length, + :policy, + :stretching, ].concat(KINDS).concat(LETTERS).freeze attr_accessor *VALID_OPTIONS @@ -18,6 +20,17 @@ def configure yield self end + def merge(params) + self.dup.merge!(params) + end + + def merge!(params) + params.keys.each do |key| + self.send("#{key}=", params[key]) + end + self + end + KINDS.each do |kind| define_method "#{kind}_chars" do self.send("letters_#{kind}") || [] @@ -29,16 +42,11 @@ def letters LETTERS.map {|l| self.send(l)}.flatten end - def to_options - { - length: self.length, - letters: self.letters - } - end - def reset self.algorithm = :sha512 self.length = 8 + self.policy = Policy.new + self.stretching = nil self.lower = true self.upper = true self.number = true @@ -47,13 +55,22 @@ def reset self.letters_number = ("0".."9").to_a end + module Writable + def configure(options = {}, &block) + Config.merge!(options) unless options.empty? + Config.configure(&block) if block_given? + end + + def policy_configure(&block) + Config.policy.configure(&block) if block_given? + end + end + module Accessible def self.included(base) base.const_set(:Config, Configuration.new) end end end - - include Configuration::Accessible end diff --git a/lib/passwd/hashlib.rb b/lib/passwd/hashlib.rb deleted file mode 100644 index d583532..0000000 --- a/lib/passwd/hashlib.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Passwd - module Hashlib - def digest(plain, _algorithm = nil) - algorithm(_algorithm || Config.algorithm).hexdigest(plain) - end - - private - def algorithm(_algorithm) - Digest.const_get(_algorithm.upcase, false) - end - end -end - diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index 28beb30..9b687df 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -1,17 +1,88 @@ module Passwd class Password include Base - include Hashlib - attr_accessor :salt - attr_reader :plain, :hash + attr_reader :plain, :hash, :salt def initialize(options = {}) + options = default_options.merge(options) + + if options.has_key?(:hash) + raise unless options.has_key?(:salt_hash) + @salt = Salt.from_hash(options[:salt_hash], self) + @hash = options[:hash] + else + @salt = + case + when options.has_key?(:salt_hash) + Salt.from_hash(options[:salt_hash], self) + when options.has_key?(:salt_plain) + Salt.from_plain(options[:salt_plain], self) + else + Salt.new(password: self) + end + self.plain = options[:plain] + end + end + + def plain=(value) + @plain = value + rehash + end + + def hash=(value, salt_hash) + @plain = nil + @hash = value + self.salt.hash = salt_hash + end + + def rehash + raise unless self.plain + @hash = digest([self.salt.hash, self.plain].join) + end + + def match?(value) + self.hash == digest([self.salt.hash, value].join) + end + + def ==(other) + match?(other) + end + + def to_s + self.plain.to_s + end + + def valid? + raise unless self.plain + + return false if Config.policy.min_length > self.plain.size + + Configuration::KINDS.each do |key| + if Config.policy.send("require_#{key}") + return false unless include_char?(Config.send("letters_#{key}")) + end + end + true + end + + def self.from_plain(value, options = {}) + new(options.merge(plain: value)) + end + + def self.from_hash(value, salt_hash) + new(hash: value, salt_hash: salt_hash) end private def default_options - {} + {plain: random} + end + + def include_char?(letters) + raise unless self.plain + self.plain.chars.uniq.each {|c| return true if letters.include?(c)} + false end end end diff --git a/lib/passwd/policy.rb b/lib/passwd/policy.rb new file mode 100644 index 0000000..bcf5643 --- /dev/null +++ b/lib/passwd/policy.rb @@ -0,0 +1,28 @@ +module Passwd + class Policy + VALID_OPTIONS = [ + :min_length, + :require_lower, + :require_upper, + :require_number + ].freeze + + attr_accessor *VALID_OPTIONS + + def initialize + reset + end + + def configure + yield self + end + + def reset + self.min_length = 8 + self.require_lower = true + self.require_upper = false + self.require_number = true + end + end +end + diff --git a/lib/passwd/salt.rb b/lib/passwd/salt.rb index c028788..2c3c5a0 100644 --- a/lib/passwd/salt.rb +++ b/lib/passwd/salt.rb @@ -1,40 +1,50 @@ module Passwd class Salt - include Hashlib + include Base attr_reader :plain, :hash def initialize(options = {}) - options.merge! default_options + options = default_options.merge(options) + + @password = options[:password] if options.has_key?(:hash) - self.hash = options[:hash] + @plain = nil + @hash = options[:hash] else - self.plain = options[:plain] || (raise ArgumentError) + @plain = options[:plain] || (raise ArgumentError) + @hash = digest_without_stretching(@plain) end end def plain=(value) @plain = value - @hash = digest(value) + @hash = digest_without_stretching(@plain) + update_password! end def hash=(value) @plain = nil @hash = value + update_password! end - def self.from_plain(value) - new(plain: value) + def self.from_plain(value, password = nil) + new(plain: value, password: password) end - def self.from_hash(value) - new(hash: value) + def self.from_hash(value, password = nil) + new(hash: value, password: password) end private def default_options {plain: Time.now.to_s} end + + def update_password! + @password.rehash if @password + end end end From f0eb0b7381ceb8df671763d6c42130a5aa9ea721 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Thu, 20 Nov 2014 23:10:13 +0900 Subject: [PATCH 04/14] Add config generator --- lib/generators/passwd/config_generator.rb | 13 ++++++++ .../passwd/templates/passwd_config.rb | 31 +++++++++++++++++++ lib/passwd.rb | 5 ++- lib/passwd/railtie.rb | 0 4 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 lib/generators/passwd/config_generator.rb create mode 100644 lib/generators/passwd/templates/passwd_config.rb create mode 100644 lib/passwd/railtie.rb diff --git a/lib/generators/passwd/config_generator.rb b/lib/generators/passwd/config_generator.rb new file mode 100644 index 0000000..83a0cfa --- /dev/null +++ b/lib/generators/passwd/config_generator.rb @@ -0,0 +1,13 @@ +module Passwd + module Generators + class ConfigGenerator < ::Rails::Generators::Base + source_root File.expand_path(File.join(File.dirname(__FILE__), "templates")) + + desc "Create Passwd configuration file" + def create_configuration_file + template "passwd_config.rb", "config/initializers/passwd.rb" + end + end + end +end + diff --git a/lib/generators/passwd/templates/passwd_config.rb b/lib/generators/passwd/templates/passwd_config.rb new file mode 100644 index 0000000..e11f9b6 --- /dev/null +++ b/lib/generators/passwd/templates/passwd_config.rb @@ -0,0 +1,31 @@ +Passwd.configure do |c| + # Password settings + # The following settings are all default values. + + # Hashing algorithm + # Supported algorithm is :md5, :rmd160, :sha1, :sha256, :sha384 and :sha512 + # c.algorithm = :sha512 + + # Random generate password length + # c.length = 8 + + # Number of hashed by stretching + # Not stretching if specified nil. + # c.stretching = nil + + # Character type that is used for password + # c.lower = true + # c.upper = true + # c.number = true +end + +Passwd.policy_configure do |c| + # Minimum password length + # c.min_length = 8 + + # Character types to force the use + # c.require_lower = true + # c.require_upper = false + # c.require_number = true +end + diff --git a/lib/passwd.rb b/lib/passwd.rb index fcd0bbc..39beca1 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -8,8 +8,7 @@ require "passwd/base" require "passwd/salt" require "passwd/password" -require "passwd/rails/railtie" -require "passwd/rails/active_record" +require "passwd/railtie" module Passwd include Configuration::Accessible @@ -44,7 +43,7 @@ def _define_to_password(salt_name, password_name) define_method :to_password do _salt_hash = self.send(salt_name) _password = self.send(password_name) - Passwd::Password.from_hash(_password, _salt_hash)) + Passwd::Password.from_hash(_password, _salt_hash) end end diff --git a/lib/passwd/railtie.rb b/lib/passwd/railtie.rb new file mode 100644 index 0000000..e69de29 From 57596fa49c1d9a5d4a87f9c2717d348a048ce78b Mon Sep 17 00:00:00 2001 From: i2bskn Date: Fri, 21 Nov 2014 02:37:28 +0900 Subject: [PATCH 05/14] for rails --- .../passwd/templates/passwd_config.rb | 10 +++ lib/passwd.rb | 64 ------------------ lib/passwd/action_controller_ext.rb | 48 ++++++++++++++ lib/passwd/active_record_ext.rb | 65 +++++++++++++++++++ lib/passwd/railtie.rb | 19 ++++++ 5 files changed, 142 insertions(+), 64 deletions(-) create mode 100644 lib/passwd/action_controller_ext.rb create mode 100644 lib/passwd/active_record_ext.rb diff --git a/lib/generators/passwd/templates/passwd_config.rb b/lib/generators/passwd/templates/passwd_config.rb index e11f9b6..160dfc0 100644 --- a/lib/generators/passwd/templates/passwd_config.rb +++ b/lib/generators/passwd/templates/passwd_config.rb @@ -29,3 +29,13 @@ # c.require_number = true end +# Session key for authentication +Rails.application.config.passwd.session_key = :user_id + +# Authentication Model Class +Rails.application.config.passwd.authenticate_class = :User + +# Redirect path when not signin +# E.G. :signin_path # Do not specify ***_url +Rails.application.config.passwd.redirect_to = nil + diff --git a/lib/passwd.rb b/lib/passwd.rb index 39beca1..996e0db 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -24,67 +24,3 @@ def self.match?(plain, salt_hash, hash) end end -if defined?(ActiveRecord) - class ActiveRecord::Base - def self.with_authenticate(options = {}) - id_name = options.fetch(:id, :email) - salt_name = options.fetch(:salt, :salt) - password_name = options.fetch(:password, :password) - - _define_to_password(salt_name, password_name) - _define_singleton_auth(id_name) - _define_instance_auth - _define_set_password(id_name, salt_name, password_name) - _define_update_password(salt_name, password_name) - end - - private - def _define_to_password(salt_name, password_name) - define_method :to_password do - _salt_hash = self.send(salt_name) - _password = self.send(password_name) - Passwd::Password.from_hash(_password, _salt_hash) - end - end - - def _define_singleton_auth(id_name) - define_singleton_method :authenticate do |_id, _pass| - user = self.find_by(id_name => _id) - user if user && user.to_password.match?(_pass) - end - end - - def _define_instance_auth - define_method :authenticate do |_pass| - self.to_password.match?(_pass) - end - end - - def _define_set_password(id_name, salt_name, password_name) - define_method :set_password do |_pass = nil| - _password = _pass || Passwd.random - _salt = self.send(salt_name) || Passwd::Salt. - _salt ||= Passwd.digest_without_stretching("#{self.send(id_name)}#{Time.now.to_s}") - self.send("#{salt_name}=", _salt) - self.send("#{password_name}=", Passwd.digest_without_stretching("#{_salt}#{_password}")) - _password - end - end - - def _define_update_password(salt_name, password_name) - define_method :update_password do |_old_pass, _new_pass, _policy = false| - _pass = self.to_password - if _pass.match?(_old_pass) - if _policy - raise unless Passwd.policy_check(_new_pass) - end - - self.set_password(_new_pass) - else - raise - end - end - end - end -end - diff --git a/lib/passwd/action_controller_ext.rb b/lib/passwd/action_controller_ext.rb new file mode 100644 index 0000000..c334202 --- /dev/null +++ b/lib/passwd/action_controller_ext.rb @@ -0,0 +1,48 @@ +module Passwd + module ActionControllerExt + extend ActiveSupport::Concern + + included do + helper_method :current_user + end + + def current_user + @current_user ||= auth_class.find_by(id: session[auth_key]) + end + + def signin!(user) + @current_user = user + session[auth_key] = user.id + end + + def signout! + @current_user = session[auth_key] = nil + end + + private + def auth_key + Rails.application.config.passwd.session_key + end + + def auth_class + @_auth_class ||= + Rails.application.config.passwd.authenticate_class.to_s.constantize + end + + def _redirect_path + _to = Rails.application.config.passwd.redirect_to + _to ? Rails.application.routes.url_helpers.send(_to) : nil + end + + def require_signin + unless current_user + if _redirect_path + redirect_to _redirect_path + else + raise + end + end + end + end +end + diff --git a/lib/passwd/active_record_ext.rb b/lib/passwd/active_record_ext.rb new file mode 100644 index 0000000..b1bb929 --- /dev/null +++ b/lib/passwd/active_record_ext.rb @@ -0,0 +1,65 @@ +module Passwd + module ActiveRecordExt + def with_authenticate(options = {}) + _id_key = options.fetch(:id, :email) + _salt_key = options.fetch(:salt, :salt) + _pass_key = options.fetch(:password, :password) + + _define_passwd(_salt_key, _pass_key) + _define_singleton_auth(_id_key) + _define_instance_auth + _define_set_password(_salt_key, _pass_key) + _define_update_password(_salt_key, _pass_key) + end + + private + def _define_passwd(_salt_key, _pass_key) + define_method :passwd do |cache = true| + return @_passwd if cache && @_passwd + self.reload + _salt, _pass = self.send(_salt_key), self.send(_pass_key) + if _salt.present? && _pass.present? + @_passwd = Passwd::Password.from_hash(_pass, _salt) + else + self.set_password + end + end + end + + def _define_singleton_auth(_id_key) + define_singleton_method :authenticate do |_id, _pass| + _condition = Array(_id_key).map {|k| "#{k} = :id"}.join(" OR ") + _user = self.find_by(_condition, id: _id) + _user if _user && _user.passwd.match?(_pass) + end + end + + def _define_instance_auth + define_method :authenticate do |_pass| + self.passwd.match?(_pass) + end + end + + def _define_set_password(_salt_key, _pass_key) + define_method :set_password do |_pass = nil| + _options = _pass ? {plain: _pass} : {} + _passwd = Passwd::Password.new(_options) + self.send("#{_salt_key}=", _passwd.salt.hash) + self.send("#{_pass_key}=", _passwd.hash) + self.instance_variable_set(:@_passwd, _passwd) + end + end + + def _define_update_password(_salt_key, _pass_key) + define_method :update_password do |_old, _new, _policy = false| + raise if _policy && Passwd.policy_check(_new) + if self.passwd.match?(_old) + self.set_password(_new) + else + raise + end + end + end + end +end + diff --git a/lib/passwd/railtie.rb b/lib/passwd/railtie.rb index e69de29..a13deda 100644 --- a/lib/passwd/railtie.rb +++ b/lib/passwd/railtie.rb @@ -0,0 +1,19 @@ +module Passwd + class Railtie < ::Rails::Railtie + config.passwd = ActiveSupport::OrderedOptions.new + + initializer "passwd" do + require "passwd/action_controller_ext" + require "passwd/active_record_ext" + + ActiveSupport.on_load(:action_controller) do + ::ActionController::Base.send(:include, Passwd::ActionControllerExt) + end + + ActiveSupport.on_load(:active_record) do + ::ActiveRecord::Base.send(:extend, Passwd::ActiveRecordExt) + end + end + end +end + From f5aff82ebcc75c2eb7259261c6c61bd739577e46 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sat, 22 Nov 2014 03:00:41 +0900 Subject: [PATCH 06/14] update README and CHANGELOG --- CHANGELOG.md | 31 ++++++- README.md | 251 +++++++++++++++++++-------------------------------- 2 files changed, 125 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f256517..f2175ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,35 @@ +## 0.2.0 + +Remake the this library. + +#### Upgrade + +1. Run the following commands. + +``` +$ bundle update passwd +$ bundle exec rails gneratate passwd:config +``` + +2. Migrate your passwd settings to `config/initializers/passwd.rb`. +3. Updates your code! + +#### Changes + +- Add extention to ActiveController. + - Add `current_user`, `signin!` and `signout!` to ActionController. + - Add `require_signin` method for `before_action`. +- Include the `Passwd::ActiveRecord` was no longer needed. +- Rename method `define_column` to `with_authenticate` in your User model. +- Rename method `Passwd.create` to `Passwd.random`. +- Rename method `Passwd.hashing` to `Passwd.digest`. +- Add `passwd` method User class. Create Passwd::Password object from target user attributes. +- Split object password and salt. + ## 0.1.5 -Features: +#### Changes - Can be specified algorithm of hashing - Change default hashing algorithm to SHA512 from SHA1 + diff --git a/README.md b/README.md index 0941d7b..43a0102 100644 --- a/README.md +++ b/README.md @@ -1,230 +1,169 @@ # Passwd -[![Gem Version](https://badge.fury.io/rb/passwd.png)](http://badge.fury.io/rb/passwd) -[![Build Status](https://travis-ci.org/i2bskn/passwd.png?branch=master)](https://travis-ci.org/i2bskn/passwd) -[![Coverage Status](https://coveralls.io/repos/i2bskn/passwd/badge.png?branch=master)](https://coveralls.io/r/i2bskn/passwd?branch=master) -[![Code Climate](https://codeclimate.com/github/i2bskn/passwd.png)](https://codeclimate.com/github/i2bskn/passwd) +[![Gem Version](https://badge.fury.io/rb/passwd.svg)](http://badge.fury.io/rb/passwd) +[![Build Status](https://travis-ci.org/i2bskn/passwd.svg?branch=master)](https://travis-ci.org/i2bskn/passwd) +[![Coverage Status](https://img.shields.io/coveralls/i2bskn/passwd.svg)](https://coveralls.io/r/i2bskn/passwd?branch=master) +[![Code Climate](https://codeclimate.com/github/i2bskn/passwd/badges/gpa.svg)](https://codeclimate.com/github/i2bskn/passwd) -Password utilities. +Password utilities and integration to Rails. ## Installation Add this line to your application's Gemfile: ```ruby -gem 'passwd' +gem "passwd" ``` And then execute: $ bundle -Or install it yourself as: - - $ gem install passwd - ## Usage -```ruby -require 'passwd' -``` +### ActiveRecord with Rails -### Create random password +Add authentication to your `User` model. +Model name is `User` by default, but can be changed in configuration file. ```ruby -password = Passwd.create +class User < ActiveRecord::Base + with_authenticate +end ``` -### Hashing password +#### Options -Hashing with SHA1. +User model The following column are required. +Column name can be changed with the specified options. -```ruby -password_hash = Passwd.hashing(password) -``` - -### Password settings +- `:id => :email` Unique value to be used for authentication. +- `:salt => :salt` Column of String to save the salt. +- `:password => :password` Column of String to save the hashed password. -Default config is stored in the class instance variable. -Changing the default configs are as follows: +Use the `name` column as id. ```ruby -Passwd.config # => Get config object. -Passwd.config(length: 10) # => Change to the default length. - -Passwd.configure do |c| - c.algorithm = :sha512 - c.length = 10 +class User < ActiveRecord::Base + with_authenticate id: :name end ``` -Options that can be specified: - -* :algorithm => Hashing algorithm. default is :sha512. -* :length => Number of characters. default is 8. -* :lower => Skip lower case if set false. default is true. -* :upper => Skip upper case if set false. default is true. -* :number => Skip numbers if set false. default is true. -* :letters_lower => Define an array of lower case. default is ("a".."z").to_a -* :letters_upper => Define an array of upper case. default is ("A".."Z").to_a -* :letters_number => Define an array of numbers. default is ("0".."9").to_a +#### Authenticate -### Policy check - -Default policy is 8 more characters and require lower case and require number. +`authenticate` method is available in both instance and class. +Returns user object if the authentication successful. +Returns nil if authentication fails or doesn't exists user. +Instance method is not required `id`. ```ruby -Passwd.policy_check("secret") # => true or false +user = User.authenticate(params[:email], params[:password]) # => return user object or nil. +user.authenticate(params[:password]) ``` -### Policy settings +`set_password` method will be set random password. +To specify password as an argument if you want to specify a password. ```ruby -Passwd.policy_configure do |c| - c.min_length = 10 -end -``` - -Options that can be specified: - -* :min_length => Number of minimum characters. default is 8. -* :require_lower => Require lower case if set true. default is true. -* :require_upper => Require upper case if set true. default is false. -* :require_number => Require number if set true. default is true. +current_user.set_password("secret") # => random password if not specified a argument. +current_user.passwd.plain # => new password +current_user.save -### Password object +new_user = User.new +password = new_user.passwd.plain +UserMailer.register(new_user, password).deliver! +``` -Default password is randomly generated. -Default salt is "#{Time.now.to_s}". +`update_password` method will be set new password if the authentication successful. +But `update_password` method doesn't call `save` method. ```ruby -password = Passwd::Password.new -password.text # return text password. -password.salt_text # return text salt. -password.salt_hash # return hash salt. -password.hash # return hash password. +# update_password(OLD_PASSWORD, NEW_PASSWORD[, POLICY_CHECK=false]) +current_user.update_password(old_pass, new_pass, true) +current_user.save ``` -Options that can be specified: - -* :password => Text password. default is random. -* :salt_text => Text salt. default is #{Time.now.to_s}. +#### Policy check -Password authenticate: +Default policy is 8 more characters and require lower case and require number. +Can be changed in configuration file. ```ruby -password = Passwd::Password.new -Passwd.auth(password.text, password.salt_hash, password.hash) # => true -Passwd.auth("invalid!!", password.salt_hash, password.hash) # => false - -password == password.text # => true -password == "invalid!!" # => false +Passwd.policy_check("secret") # => true or false ``` -## For ActiveRecord +### ActionController -### User model +Already several methods is available in your controller. -Include `Passwd::ActiveRecord` module and define id/salt/password column from `define_column` method. -`id` column is required uniqueness. +If you want to authenticate the application. +Unauthorized access is thrown exception. +Can be specified to redirect in configuration file. ```ruby -class User < ActiveRecord::Base - include Passwd::ActiveRecord - # if not specified arguments for define_column => {id: :email, salt: :salt, password: :password} - define_column id: :id_colname, salt: :salt_colname, password: :password_colname - - ... +class ApplicationController < ActionController::Base + before_action :require_signin end ``` -Available following method by defining id/salt/password column. - -### Authentication - -`authenticate` method is available in both instance and class. -Return the user object if the authentication successful. -Return the nil if authentication fails or doesn't exists user. +If you want to implement the session management. ```ruby -user = User.authenticate(params[:email], params[:password]) # => return user object or nil. - -if user - session[:user] = user.id - redirect_to bar_path, notice: "Hello #{user.name}!" -else - flash.now[:alert] = "Authentication failed" - render action: :new +class SessionsController < ApplicationController + # If you has been enabled `require_signin` in ApplicationController + skip_before_action :require_signin + + # GET /signin + def new; end + + # POST /signin + def create + # Returns nil or user + @user = User.authenticate(params[:email], params[:password]) + + if @user + # Save user_id to session + signin!(@user) + redirect_to some_url, notice: "Signin was successful. Hello #{current_user.name}" + else # Authentication fails + render action: :new + end + end + + # DELETE /signout + def destroy + # Clear session (Only user_id) + signout! + end end ``` -instance method is not required `id`. +`current_user` method available if already signin. ```ruby -current_user = User.find(session[:user]) - -if current_user.authenticate(params[:password]) # => return true or false - # some process - redirect_to bar_path, notice: "Some process is successfully" -else - flash.now[:alert] = "Authentication failed" - render action: :edit +# app/controllers/greet_controller.rb +def greet + render text: "Hello #{current_user.name}!!" end -``` -### Change passowrd +# app/views/greet/greet.html.erb +

Hello <%= current_user.name %>!!

+``` -`set_password` method will be set random password. -Return value is plain text password. -To specify the password as an argument if you want to specify a password. -`salt` also set if salt is nil. +### Generate configuration file -```ruby -current_user = User.find(session[:user]) -password_text = current_user.set_password +Run generator of Rails. +Configuration file created to `config/initializers/passwd.rb`. -if current_user.save - redirect_to bar_path, notice: "Password update successfully" -else - render action: :edit -end ``` - -`update_password` method will be set new password if the authentication successful. -But `update_password` method doesn't call `save` method. - -```ruby -current_user = User.find(session[:user]) - -begin - Passwd.confirm_check(params[:password], params[:password_confirmation]) - # update_password(OLD_PASSWORD, NEW_PASSWORD[, POLICY_CHECK=false]) - current_user.update_password(old_pass, new_pass, true) - current_user.save! - redirect_to bar_path, notice: "Password updated successfully" -rescue Passwd::PasswordNotMatch - # PASSWORD != PASSWORD_CONFIRMATION from Passwd.#confirm_check - flash.now[:alert] = "Password not match" - render action: :edit -rescue Passwd::AuthError - # Authentication failed from #update_password - flash.now[:alert] = "Password is incorrect" - render action: :edit -rescue Passwd::PolicyNotMatch - # Policy not match from #update_password - flash.now[:alert] = "Policy not match" - render action: :edit -rescue - # Other errors - flash.now[:alert] = "Password update failed" - render action: :edit -end +$ bundle exec rails generate passwd:config ``` ## Contributing -1. Fork it +1. Fork it ( https://github.com/i2bskn/passwd/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Added some feature'`) +3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request +5. Create a new Pull Request + From 1e4e5811dffb175fc2e51c40a0f2174505183d29 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sat, 22 Nov 2014 03:17:57 +0900 Subject: [PATCH 07/14] organize exeptions --- lib/passwd/action_controller_ext.rb | 6 +++--- lib/passwd/active_record_ext.rb | 4 ++-- lib/passwd/configuration.rb | 2 +- lib/passwd/errors.rb | 5 +++-- lib/passwd/password.rb | 8 ++++---- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/lib/passwd/action_controller_ext.rb b/lib/passwd/action_controller_ext.rb index c334202..750c33a 100644 --- a/lib/passwd/action_controller_ext.rb +++ b/lib/passwd/action_controller_ext.rb @@ -21,12 +21,12 @@ def signout! private def auth_key - Rails.application.config.passwd.session_key + Rails.application.config.passwd.session_key || :user_id end def auth_class @_auth_class ||= - Rails.application.config.passwd.authenticate_class.to_s.constantize + (Rails.application.config.passwd.authenticate_class || :User).to_s.constantize end def _redirect_path @@ -39,7 +39,7 @@ def require_signin if _redirect_path redirect_to _redirect_path else - raise + raise UnauthorizedAccess end end end diff --git a/lib/passwd/active_record_ext.rb b/lib/passwd/active_record_ext.rb index b1bb929..79fa8fc 100644 --- a/lib/passwd/active_record_ext.rb +++ b/lib/passwd/active_record_ext.rb @@ -52,11 +52,11 @@ def _define_set_password(_salt_key, _pass_key) def _define_update_password(_salt_key, _pass_key) define_method :update_password do |_old, _new, _policy = false| - raise if _policy && Passwd.policy_check(_new) + raise PolicyNotMatch if _policy && !Passwd.policy_check(_new) if self.passwd.match?(_old) self.set_password(_new) else - raise + raise AuthenticationFails end end end diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb index eba9302..f84c4b4 100644 --- a/lib/passwd/configuration.rb +++ b/lib/passwd/configuration.rb @@ -38,7 +38,7 @@ def merge!(params) end def letters - KINDS.detect {|k| self.send(k)} || (raise "letters is empty") + KINDS.detect {|k| self.send(k)} || (raise ConfigError, "letters is empry.") LETTERS.map {|l| self.send(l)}.flatten end diff --git a/lib/passwd/errors.rb b/lib/passwd/errors.rb index 7079c44..4e1c0d8 100644 --- a/lib/passwd/errors.rb +++ b/lib/passwd/errors.rb @@ -1,7 +1,8 @@ module Passwd class PasswdError < StandardError; end - class AuthError < PasswdError; end - class PasswordNotMatch < PasswdError; end + class UnauthorizedAccess < PasswdError; end class PolicyNotMatch < PasswdError; end + class AuthenticationFails < PasswdError; end + class ConfigError < PasswdError; end end diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index 9b687df..6fe296e 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -8,7 +8,7 @@ def initialize(options = {}) options = default_options.merge(options) if options.has_key?(:hash) - raise unless options.has_key?(:salt_hash) + raise ArgumentError unless options.has_key?(:salt_hash) @salt = Salt.from_hash(options[:salt_hash], self) @hash = options[:hash] else @@ -37,7 +37,7 @@ def hash=(value, salt_hash) end def rehash - raise unless self.plain + raise PasswdError unless self.plain @hash = digest([self.salt.hash, self.plain].join) end @@ -54,7 +54,7 @@ def to_s end def valid? - raise unless self.plain + raise PasswdError unless self.plain return false if Config.policy.min_length > self.plain.size @@ -80,7 +80,7 @@ def default_options end def include_char?(letters) - raise unless self.plain + raise PasswdError unless self.plain self.plain.chars.uniq.each {|c| return true if letters.include?(c)} false end From 4de14ac1d3df212c98f9fc9f15c022de34ef1e58 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sat, 22 Nov 2014 21:47:43 +0900 Subject: [PATCH 08/14] remove old specs --- Rakefile | 1 + spec/passwd/.keep | 0 spec/passwd/active_record_spec.rb | 159 ----------- spec/passwd/base_spec.rb | 234 ---------------- spec/passwd/configuration/config_spec.rb | 248 ----------------- spec/passwd/configuration/policy_spec.rb | 132 ---------- spec/passwd/configuration/tmp_config_spec.rb | 264 ------------------- spec/passwd/password_spec.rb | 148 ----------- spec/spec_helper.rb | 5 +- 9 files changed, 2 insertions(+), 1189 deletions(-) create mode 100644 spec/passwd/.keep delete mode 100644 spec/passwd/active_record_spec.rb delete mode 100644 spec/passwd/base_spec.rb delete mode 100644 spec/passwd/configuration/config_spec.rb delete mode 100644 spec/passwd/configuration/policy_spec.rb delete mode 100644 spec/passwd/configuration/tmp_config_spec.rb delete mode 100644 spec/passwd/password_spec.rb diff --git a/Rakefile b/Rakefile index 25e1c41..1724416 100644 --- a/Rakefile +++ b/Rakefile @@ -7,3 +7,4 @@ RSpec::Core::RakeTask.new(:spec) do |t| end task :default => :spec + diff --git a/spec/passwd/.keep b/spec/passwd/.keep new file mode 100644 index 0000000..e69de29 diff --git a/spec/passwd/active_record_spec.rb b/spec/passwd/active_record_spec.rb deleted file mode 100644 index bc74017..0000000 --- a/spec/passwd/active_record_spec.rb +++ /dev/null @@ -1,159 +0,0 @@ -require "spec_helper" - -describe Passwd::ActiveRecord do - class User - include Passwd::ActiveRecord - define_column - end - - let(:salt) {Digest::SHA512.hexdigest("salt")} - let(:password_text) {"secret"} - let(:password_hash) {Digest::SHA512.hexdigest("#{salt}#{password_text}")} - - describe ".#included" do - it "define singleton methods" do - expect(User.respond_to? :define_column).to be_truthy - end - end - - describe "extend methods" do - describe ".#define_column" do - let(:user) {User.new} - - it "define singleton methods" do - expect(User.respond_to? :authenticate).to be_truthy - end - - it "define authenticate method" do - expect(user.respond_to? :authenticate).to be_truthy - end - - it "define set_password method" do - expect(user.respond_to? :set_password).to be_truthy - end - - it "define update_password" do - expect(user.respond_to? :update_password).to be_truthy - end - end - end - - describe "defined methods from define_column" do - describe ".#authenticate" do - let!(:record) { - record = double("record mock") - allow(record).to receive_messages(salt: salt, password: password_hash) - response = record - allow(User).to receive(:find_by) {response} - record - } - - it "user should be returned if authentication is successful" do - expect(User).to receive(:find_by) - expect(User.authenticate("valid_id", password_text)).to eq(record) - end - - it "should return nil if authentication failed" do - expect(User).to receive(:find_by) - expect(User.authenticate("valid_id", "invalid_secret")).to be_nil - end - - it "should return nil if user not found" do - expect(User).to receive(:find_by).with(email: "invalid_id") {nil} - expect(User.authenticate("invalid_id", password_text)).to be_nil - end - end - - describe "#authenticate" do - let!(:user) { - user = User.new - allow(user).to receive_messages(salt: salt, password: password_hash) - user - } - - it "should return true if authentication is successful" do - expect(user.authenticate(password_text)).to be_truthy - end - - it "should return false if authentication failed" do - expect(user.authenticate("invalid_pass")).to be_falsey - end - end - - describe "#set_password" do - let!(:user) { - user = User.new - allow(user).to receive(:salt) {salt} - user - } - - it "should return set password" do - expect(user).to receive(:salt=).with(salt) - expect(user).to receive(:password=).with(Passwd.hashing("#{salt}#{password_text}")) - expect(user.set_password(password_text)).to eq(password_text) - end - - it "should set random password if not specified" do - expect(user).to receive(:salt=).with(salt) - random_password = Passwd.create - expect(Passwd).to receive(:create) {random_password} - expect(user).to receive(:password=).with(Passwd.hashing("#{salt}#{random_password}")) - user.set_password - end - - it "should set salt if salt is nil" do - mail_addr = "foo@example.com" - time_now = Time.now - salt2 = Passwd.hashing("#{mail_addr}#{time_now.to_s}") - allow(Time).to receive(:now) {time_now} - allow(user).to receive(:email) {mail_addr} - expect(user).to receive(:salt) {nil} - expect(user).to receive(:salt=).with(salt2) - expect(user).to receive(:password=).with(Passwd.hashing("#{salt2}#{password_text}")) - user.set_password(password_text) - end - end - - describe "#update_password" do - let!(:user) { - user = User.new - allow(user).to receive(:salt) {salt} - allow(user).to receive(:password) {password_hash} - user - } - - context "without policy check" do - it "should return update password" do - pass = "new_password" - expect(user).to receive(:set_password).with(pass) {pass} - expect(user.update_password(password_text, pass)).to eq(pass) - end - - it "should generate exception if authentication failed" do - expect(Passwd).to receive(:auth) {false} - expect(user).not_to receive(:set_password) - expect { - user.update_password("invalid_password", "new_password") - }.to raise_error(Passwd::AuthError) - end - end - - context "with policy check" do - it "should return update password" do - pass = "new_password" - expect(Passwd).to receive(:policy_check) {true} - expect(user).to receive(:set_password).with(pass) {pass} - expect(user.update_password(password_text, pass, true)).to eq(pass) - end - - it "should generate exception if policy not match" do - pass = "new_password" - expect(Passwd).to receive(:policy_check) {false} - expect { - user.update_password(password_text, pass, true) - }.to raise_error(Passwd::PolicyNotMatch) - end - end - end - end -end diff --git a/spec/passwd/base_spec.rb b/spec/passwd/base_spec.rb deleted file mode 100644 index d968ea2..0000000 --- a/spec/passwd/base_spec.rb +++ /dev/null @@ -1,234 +0,0 @@ -require "spec_helper" - -describe Passwd do - describe "extended Base" do - describe "#create" do - context "without arguments" do - let(:password) {Passwd.create} - - it "TmpConfig should not be generated" do - expect(Passwd::TmpConfig).not_to receive(:new) - expect{password}.not_to raise_error - end - - it "created password should be String object" do - expect(password.is_a? String).to be_truthy - end - - it "created password length should be default length" do - expect(password.size).to eq(8) - end - end - - context "with arguments" do - it "TmpConfig should be generated" do - tmp_config = double("tmp_config mock", length: 8, letters: ["a", "b"]) - expect(Passwd::TmpConfig).to receive(:new) {tmp_config} - expect{Passwd.create(length: 10)}.not_to raise_error - end - - it "password was created specified characters" do - expect(Passwd.create(length: 10).size).to eq(10) - end - - it "password create without lower case" do - expect(("a".."z").to_a.include? Passwd.create(lower: false)).to be_falsey - end - - it "password create without upper case" do - expect(("A".."Z").to_a.include? Passwd.create(upper: false)).to be_falsey - end - - it "password create without number" do - expect(("0".."9").to_a.include? Passwd.create(number: false)).to be_falsey - end - end - end - - describe "#auth" do - let!(:password) do - password = Passwd.create - salt_hash = Passwd.hashing(Time.now.to_s) - password_hash = Passwd.hashing("#{salt_hash}#{password}") - {text: password, salt: salt_hash, hash: password_hash} - end - - it "return true with valid password" do - expect(Passwd.auth(password[:text], password[:salt], password[:hash])).to be_truthy - end - - it "return false with invalid password" do - expect(Passwd.auth("invalid", password[:salt], password[:hash])).to be_falsey - end - - it "should create exception if not specified arguments" do - expect(proc{Passwd.auth}).to raise_error - end - end - - describe "#hashing" do - it "should call SHA512.#hexdigest" do - expect(Digest::SHA512).to receive(:hexdigest) - Passwd.hashing("secret") - end - - it "return hashed password" do - hashed = Digest::SHA512.hexdigest "secret" - expect(Passwd.hashing("secret")).to eq(hashed) - end - - it "return hashed password specified algorithm" do - hashed = Digest::SHA256.hexdigest "secret" - expect(Passwd.hashing("secret", :sha256)).to eq(hashed) - end - - it "should create exception if not specified argument" do - expect(proc{Passwd.hashing}).to raise_error - end - end - - describe "#confirm_check" do - context "with out policy check" do - it "should generate exception if password don't match" do - expect{ - Passwd.confirm_check("secret", "invalid") - }.to raise_error(Passwd::PasswordNotMatch) - end - - it "return true if password matches" do - expect(Passwd.confirm_check("secret", "secret")).to be_truthy - end - end - - context "with policy check" do - it "return false if invalid password by policy" do - expect(Passwd.confirm_check("secret", "secret", true)).to be_falsey - end - - it "return true if valid password by policy" do - expect(Passwd.confirm_check("secretpass", "secretpass", true)).to be_falsey - end - end - end - - describe "#configure" do - it "return configuration object" do - expect(Passwd.configure.is_a? Passwd::Config).to be_truthy - end - - it "set config value from block" do - Passwd.configure do |c| - c.length = 10 - end - expect(Passwd.configure.length).not_to eq(8) - expect(Passwd.configure.length).to eq(10) - end - - it "set config value from hash" do - Passwd.configure length: 20 - expect(Passwd.config.length).not_to eq(8) - expect(Passwd.config.length).to eq(20) - end - - it "alias of configure as config" do - expect(Passwd.configure.object_id).to eq(Passwd.config.object_id) - end - end - - describe "#policy_configure" do - it "return policy object" do - expect(Passwd.policy_configure.is_a? Passwd::Policy).to be_truthy - end - - it "set policy value from block" do - Passwd.policy_configure do |c| - c.min_length = 10 - end - expect(Passwd.policy_configure.min_length).not_to eq(8) - expect(Passwd.policy_configure.min_length).to eq(10) - end - end - - describe "#policy_check" do - it "Policy#valid? should be called" do - expect(Passwd::Policy.instance).to receive(:valid?).with("secret1234" ,Passwd::Config.instance) - Passwd.policy_check("secret1234") - end - end - - describe "#reset_policy" do - let(:policy) {Passwd::Policy.instance} - - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - Passwd.reset_policy - } - - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "number should be a default" do - expect(policy.require_number).to be_truthy - end - end - - describe "#reset_config" do - let(:config) {Passwd::Config.instance} - - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - Passwd.reset_config - } - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end - end -end diff --git a/spec/passwd/configuration/config_spec.rb b/spec/passwd/configuration/config_spec.rb deleted file mode 100644 index 815ced0..0000000 --- a/spec/passwd/configuration/config_spec.rb +++ /dev/null @@ -1,248 +0,0 @@ -require "spec_helper" - -describe Passwd::Config do - let(:config) {Passwd::Config.instance} - - describe "defined accessors" do - it "defined algorithm" do - expect(config.respond_to? :algorithm).to be_truthy - end - - it "defined length" do - expect(config.respond_to? :length).to be_truthy - end - - it "defined lower" do - expect(config.respond_to? :lower).to be_truthy - end - - it "defined upper" do - expect(config.respond_to? :upper).to be_truthy - end - - it "defined number" do - expect(config.respond_to? :number).to be_truthy - end - - it "defined letters_lower" do - expect(config.respond_to? :letters_lower).to be_truthy - end - - it "defined letters_upper" do - expect(config.respond_to? :letters_upper).to be_truthy - end - - it "defined letters_number" do - expect(config.respond_to? :letters_number).to be_truthy - end - end - - describe "#initialize" do - it "algorithm should be a default" do - expect(config.algorithm).to eq(:sha512) - end - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end - - describe "#configure" do - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - } - - it "set length from block" do - expect(config.length).to eq(20) - end - - it "set lower from block" do - expect(config.lower).to be_falsey - end - - it "set upper from block" do - expect(config.upper).to be_falsey - end - - it "set number from block" do - expect(config.number).to be_falsey - end - - it "set letters_lower from block" do - expect(config.letters_lower).to eq(["a"]) - end - - it "set letters_upper from block" do - expect(config.letters_upper).to eq(["A"]) - end - - it "set letters_number from block" do - expect(config.letters_number).to eq(["0"]) - end - - it "raise error unknown setting" do - expect { - config.configure do |c| - c.unknown = true - end - }.to raise_error - end - end - - describe "#merge" do - it "set length from hash" do - config.merge(length: 10) - expect(config.length).to eq(10) - end - - it "set lower from hash" do - config.merge(lower: false) - expect(config.lower).to be_falsey - end - - it "set upper from hash" do - config.merge(upper: false) - expect(config.upper).to be_falsey - end - - it "set number from hash" do - config.merge(number: false) - expect(config.number).to be_falsey - end - - it "set letters_lower from hash" do - config.merge(letters_lower: ["a"]) - expect(config.letters_lower).to eq(["a"]) - end - - it "set letters_upper from hash" do - config.merge(letters_upper: ["A"]) - expect(config.letters_upper).to eq(["A"]) - end - - it "set letters_number from hash" do - config.merge(letters_number: ["0"]) - expect(config.letters_number).to eq(["0"]) - end - - it "raise error unknown setting" do - expect { - config.merge(unknown: true) - }.to raise_error - end - end - - describe "#letters" do - it "return Array object" do - expect(config.letters.is_a? Array).to be_truthy - end - - it "all elements of the string" do - config.letters.each do |l| - expect(l.is_a? String).to be_truthy - end - end - - it "return all letters" do - all_letters = ("a".."z").to_a.concat(("A".."Z").to_a).concat(("0".."9").to_a) - expect(config.letters).to eq(all_letters) - end - - it "return except for the lower case" do - config.merge(lower: false) - expect(config.letters.include? "a").to be_falsey - end - - it "return except for the upper case" do - config.merge(upper: false) - expect(config.letters.include? "A").to be_falsey - end - - it "return except for the number case" do - config.merge(number: false) - expect(config.letters.include? "0").to be_falsey - end - - it "raise error if letters is empty" do - config.merge(lower: false, upper: false, number: false) - expect { - config.letters - }.to raise_error - end - end - - describe "#reset" do - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - config.reset - } - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end -end diff --git a/spec/passwd/configuration/policy_spec.rb b/spec/passwd/configuration/policy_spec.rb deleted file mode 100644 index 59acc94..0000000 --- a/spec/passwd/configuration/policy_spec.rb +++ /dev/null @@ -1,132 +0,0 @@ -require "spec_helper" - -describe Passwd::Policy do - let(:policy) {Passwd::Policy.instance} - - describe "defined accessors" do - it "defined min_length" do - expect(policy.respond_to? :min_length).to be_truthy - end - - it "defined require_lower" do - expect(policy.respond_to? :require_lower).to be_truthy - end - - it "defined require_upper" do - expect(policy.respond_to? :require_upper).to be_truthy - end - - it "defined require_number" do - expect(policy.respond_to? :require_number).to be_truthy - end - end - - describe "#initialize" do - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "require_upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "require_number should be a default" do - expect(policy.require_number).to be_truthy - end - end - - describe "#configure" do - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - } - - it "set min_length from block" do - expect(policy.min_length).to eq(20) - end - - it "set require_lower from block" do - expect(policy.require_lower).to be_falsey - end - - it "set require_upper from block" do - expect(policy.require_upper).to be_truthy - end - - it "set require_number from block" do - expect(policy.require_number).to be_falsey - end - end - - describe "#valid?" do - let(:config) {Passwd::Config.instance} - - it "valid password should be valid" do - expect(policy.valid?("secret1234", config)).to be_truthy - end - - it "short password should not valid" do - expect(policy.valid?("short1", config)).to be_falsey - end - - it "password should not valid if not contain lower case" do - expect(policy.valid?("NOTLOWER12", config)).to be_falsey - end - - it "password should not valid if not contain upper case" do - policy.configure {|c| c.require_upper = true} - expect(policy.valid?("notupper12", config)).to be_falsey - end - - it "password should not valid if not contain number" do - expect(policy.valid?("notnumber", config)).to be_falsey - end - end - - describe "#include_char?" do - it "should be return true if contains" do - expect(policy.include_char?(("a".."z").to_a, "contains")).to be_truthy - end - - it "should be return false if not contains" do - expect(policy.include_char?(("a".."z").to_a, "NOTCONTAINS")).to be_falsey - end - end - - describe "#reset" do - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - policy.reset - } - - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "require_upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "require_number should be a default" do - expect(policy.require_number).to be_truthy - end - end -end - diff --git a/spec/passwd/configuration/tmp_config_spec.rb b/spec/passwd/configuration/tmp_config_spec.rb deleted file mode 100644 index 7eba00a..0000000 --- a/spec/passwd/configuration/tmp_config_spec.rb +++ /dev/null @@ -1,264 +0,0 @@ -require "spec_helper" - -describe Passwd::TmpConfig do - let(:config) {Passwd::Config.instance} - - def tmp_config(options={}) - Passwd::TmpConfig.new(Passwd::Config.instance, options) - end - - describe "defined accessors" do - it "defined algorithm" do - expect(config.respond_to? :algorithm).to be_truthy - end - - it "defined length" do - expect(tmp_config.respond_to? :length).to be_truthy - end - - it "defined lower" do - expect(tmp_config.respond_to? :lower).to be_truthy - end - - it "defined upper" do - expect(tmp_config.respond_to? :upper).to be_truthy - end - - it "defined number" do - expect(tmp_config.respond_to? :number).to be_truthy - end - - it "defined letters_lower" do - expect(tmp_config.respond_to? :letters_lower).to be_truthy - end - - it "defined letters_upper" do - expect(tmp_config.respond_to? :letters_upper).to be_truthy - end - - it "defined letters_number" do - expect(tmp_config.respond_to? :letters_number).to be_truthy - end - end - - describe "#initialize" do - context "with empty options" do - it "algorithm should be a default" do - expect(config.algorithm).to eq(:sha512) - end - - it "length should be a default" do - expect(tmp_config.length).to eq(8) - end - - it "lower should be a default" do - expect(tmp_config.lower).to be_truthy - end - - it "upper should be a default" do - expect(tmp_config.upper).to be_truthy - end - - it "number should be a default" do - expect(tmp_config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(tmp_config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(tmp_config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(tmp_config.letters_number).to eq(("0".."9").to_a) - end - end - - context "with options" do - it "length should be a specified params" do - expect(tmp_config(length: 10).length).to eq(10) - expect(config.length).to eq(8) - end - - it "lower should be a specified params" do - expect(tmp_config(lower: false).lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "upper should be a specified params" do - expect(tmp_config(upper: false).upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "number should be a specified params" do - expect(tmp_config(number: false).number).to be_falsey - expect(config.number).to be_truthy - end - - it "letters_lower should be a specified params" do - expect(tmp_config(letters_lower: ["a"]).letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a specified params" do - expect(tmp_config(letters_upper: ["A"]).letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a specified params" do - expect(tmp_config(letters_number: ["0"]).letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - end - end - - describe "#configure" do - let(:changed_tmp_config) do - tconf = tmp_config - tconf.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - tconf - end - - it "set length from block" do - expect(changed_tmp_config.length).to eq(20) - expect(config.length).to eq(8) - end - - it "set lower from block" do - expect(changed_tmp_config.lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "set upper from block" do - expect(changed_tmp_config.upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "set number from block" do - expect(changed_tmp_config.number).to be_falsey - expect(config.number).to be_truthy - end - - it "set letters_lower from block" do - expect(changed_tmp_config.letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "set letters_upper from block" do - expect(changed_tmp_config.letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "set letters_number from block" do - expect(changed_tmp_config.letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - - it "raise error unknown setting" do - expect { - tmp_config.configure do |c| - c.unknown = true - end - }.to raise_error - end - end - - describe "#merge" do - let(:default_tmp_config) {tmp_config} - - it "set length from hash" do - default_tmp_config.merge(length: 10) - expect(default_tmp_config.length).to eq(10) - expect(config.length).to eq(8) - end - - it "set lower from hash" do - default_tmp_config.merge(lower: false) - expect(default_tmp_config.lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "set upper from hash" do - default_tmp_config.merge(upper: false) - expect(default_tmp_config.upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "set number from hash" do - default_tmp_config.merge(number: false) - expect(default_tmp_config.number).to be_falsey - expect(config.number).to be_truthy - end - - it "set letters_lower from hash" do - default_tmp_config.merge(letters_lower: ["a"]) - expect(default_tmp_config.letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "set letters_upper from hash" do - default_tmp_config.merge(letters_upper: ["A"]) - expect(default_tmp_config.letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "set letters_number from hash" do - default_tmp_config.merge(letters_number: ["0"]) - expect(default_tmp_config.letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - - it "raise error unknown setting" do - expect { - tmp_config.merge(unknown: true) - }.to raise_error - end - end - - describe "#letters" do - it "return Array object" do - expect(tmp_config.letters.is_a? Array).to be_truthy - end - - it "all elements of the string" do - tmp_config.letters.each do |l| - expect(l.is_a? String).to be_truthy - end - end - - it "return all letters" do - all_letters = ("a".."z").to_a.concat(("A".."Z").to_a).concat(("0".."9").to_a) - expect(tmp_config.letters).to eq(all_letters) - end - - it "return except for the lower case" do - expect(tmp_config(lower: false).letters.include? "a").to be_falsey - end - - it "return except for the upper case" do - expect(tmp_config(upper: false).letters.include? "A").to be_falsey - end - - it "return except for the number case" do - expect(tmp_config(number: false).letters.include? "0").to be_falsey - end - - it "raise error if letters is empty" do - tconf = tmp_config(lower: false, upper: false, number: false) - expect { - tconf.letters - }.to raise_error - end - end -end - diff --git a/spec/passwd/password_spec.rb b/spec/passwd/password_spec.rb deleted file mode 100644 index 1007bdb..0000000 --- a/spec/passwd/password_spec.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "spec_helper" - -describe Passwd::Password do - let(:password) {Passwd::Password.new} - - describe "#initialize" do - context "with default params" do - let!(:password_text) { - password_text = Passwd.create - expect(Passwd).to receive(:create) {password_text} - password_text - } - - let!(:time_now) { - time_now = Time.now - expect(Time).to receive(:now) {time_now} - time_now - } - - it "@text should be a random password" do - expect(password.text.size).to eq(8) - expect(password.text).to eq(password_text) - end - - it "@salt_text should be a auto created" do - expect(password.salt_text).to eq(time_now.to_s) - end - - it "@salt_hash should be a hashed salt" do - expect(password.salt_hash).to eq(Passwd.hashing(time_now.to_s)) - end - - it "@password_hash should be a hashed password with salt" do - password_hash = Passwd.hashing("#{Passwd.hashing(time_now.to_s)}#{password_text}") - expect(password.hash).to eq(password_hash) - end - end - - context "with custom params" do - let(:password_text) {Passwd.create} - let(:salt_text) {"salt"} - let!(:time_now) { - time_now = Time.now - allow(Time).to receive(:create) {time_now} - time_now - } - - it "@text is specified password" do - password = Passwd::Password.new(password: password_text) - expect(password.text).to eq(password_text) - end - - it "@hash is hash of specified password" do - password = Passwd::Password.new(password: password_text) - password_hash = Passwd.hashing("#{Passwd.hashing(time_now.to_s)}#{password_text}") - expect(password.hash).to eq(password_hash) - end - - it "@salt_text is specified salt" do - password = Passwd::Password.new(salt_text: salt_text) - expect(password.salt_text).to eq(salt_text) - end - - it "@salt_hash is hash of specified salt" do - salt_hash = Passwd.hashing(salt_text) - password = Passwd::Password.new(salt_text: salt_text) - expect(password.salt_hash).to eq(salt_hash) - end - end - end - - describe "#text=" do - it "@text is changed" do - old_password = password.text - password.text = password.text.reverse - expect(password.text).not_to eq(old_password) - end - - it "@hash is changed" do - old_hash = password.hash - new_password = password.text = password.text.reverse - expect(password.hash).not_to eq(old_hash) - expect(password.hash).to eq(Passwd.hashing("#{password.salt_hash}#{new_password}")) - end - end - - describe "#hash=" do - it "@text is nil" do - password.hash = Passwd.hashing("secret") - expect(password.text).to be_nil - end - - it "@hash is changed" do - old_hash = password.hash - password.hash = Passwd.hashing("secret") - expect(password.hash).not_to eq(old_hash) - end - end - - describe "#salt_text=" do - it "@salt_text is changed" do - old_salt = password.salt_text - password.salt_text = "salt" - expect(password.salt_text).not_to eq(old_salt) - end - - it "@salt_hash is changed" do - old_salt = password.salt_hash - password.salt_text = "salt" - expect(password.salt_hash).not_to eq(old_salt) - end - - it "@hash is changed" do - old_hash = password.hash - password.salt_text = "salt" - expect(password.hash).not_to eq(old_hash) - end - end - - describe "#salt_hash=" do - it "@salt_text is nil" do - password.salt_hash = Passwd.hashing("salt") - expect(password.salt_text).to eq(nil) - end - - it "@salt_hash is changed" do - old_salt_hash = password.salt_hash - password.salt_hash = Passwd.hashing("salt") - expect(password.salt_hash).not_to eq(old_salt_hash) - end - - it "@hash is changed" do - old_hash = password.hash - password.salt_hash = Passwd.hashing("salt") - expect(password.hash).not_to eq(old_hash) - end - end - - describe "#==" do - it "return true with valid password" do - expect(password == password.text).to be_truthy - end - - it "return false with invalid password" do - expect(password == "secret").to be_falsey - end - end -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 832c1a0..a1a3049 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -16,8 +16,5 @@ RSpec.configure do |config| config.order = "random" - config.after do - Passwd::Config.instance.reset - Passwd::Policy.instance.reset - end end + From 2ab2a38e0a478ec195c0880b8b5aaec62d7cf331 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sat, 22 Nov 2014 23:23:10 +0900 Subject: [PATCH 09/14] Add example application --- example/.gitignore | 16 ++++ example/Gemfile | 21 +++++ example/README.rdoc | 28 +++++++ example/Rakefile | 6 ++ example/app/assets/images/.keep | 0 example/app/assets/javascripts/application.js | 16 ++++ .../app/assets/stylesheets/application.css | 15 ++++ .../app/controllers/application_controller.rb | 5 ++ example/app/controllers/concerns/.keep | 0 example/app/helpers/application_helper.rb | 2 + example/app/mailers/.keep | 0 example/app/models/.keep | 0 example/app/models/concerns/.keep | 0 .../app/views/layouts/application.html.erb | 14 ++++ example/bin/bundle | 3 + example/bin/rails | 4 + example/bin/rake | 4 + example/config.ru | 4 + example/config/application.rb | 30 +++++++ example/config/boot.rb | 4 + example/config/database.yml | 26 +++++++ example/config/environment.rb | 5 ++ example/config/environments/development.rb | 37 +++++++++ example/config/environments/production.rb | 78 +++++++++++++++++++ example/config/environments/test.rb | 39 ++++++++++ example/config/initializers/assets.rb | 8 ++ .../initializers/backtrace_silencers.rb | 7 ++ .../config/initializers/cookies_serializer.rb | 3 + .../initializers/filter_parameter_logging.rb | 4 + example/config/initializers/inflections.rb | 16 ++++ example/config/initializers/mime_types.rb | 4 + example/config/initializers/passwd.rb | 41 ++++++++++ example/config/initializers/session_store.rb | 3 + .../config/initializers/wrap_parameters.rb | 14 ++++ example/config/locales/en.yml | 23 ++++++ example/config/routes.rb | 56 +++++++++++++ example/config/secrets.yml | 22 ++++++ example/db/seeds.rb | 7 ++ example/lib/assets/.keep | 0 example/lib/tasks/.keep | 0 example/log/.keep | 0 example/public/404.html | 67 ++++++++++++++++ example/public/422.html | 67 ++++++++++++++++ example/public/500.html | 66 ++++++++++++++++ example/public/favicon.ico | 0 example/public/robots.txt | 5 ++ example/vendor/assets/javascripts/.keep | 0 example/vendor/assets/stylesheets/.keep | 0 passwd.gemspec | 4 +- spec/passwd/active_record_ext_spec.rb | 8 ++ spec/spec_helper.rb | 3 + 51 files changed, 784 insertions(+), 1 deletion(-) create mode 100644 example/.gitignore create mode 100644 example/Gemfile create mode 100644 example/README.rdoc create mode 100644 example/Rakefile create mode 100644 example/app/assets/images/.keep create mode 100644 example/app/assets/javascripts/application.js create mode 100644 example/app/assets/stylesheets/application.css create mode 100644 example/app/controllers/application_controller.rb create mode 100644 example/app/controllers/concerns/.keep create mode 100644 example/app/helpers/application_helper.rb create mode 100644 example/app/mailers/.keep create mode 100644 example/app/models/.keep create mode 100644 example/app/models/concerns/.keep create mode 100644 example/app/views/layouts/application.html.erb create mode 100755 example/bin/bundle create mode 100755 example/bin/rails create mode 100755 example/bin/rake create mode 100644 example/config.ru create mode 100644 example/config/application.rb create mode 100644 example/config/boot.rb create mode 100644 example/config/database.yml create mode 100644 example/config/environment.rb create mode 100644 example/config/environments/development.rb create mode 100644 example/config/environments/production.rb create mode 100644 example/config/environments/test.rb create mode 100644 example/config/initializers/assets.rb create mode 100644 example/config/initializers/backtrace_silencers.rb create mode 100644 example/config/initializers/cookies_serializer.rb create mode 100644 example/config/initializers/filter_parameter_logging.rb create mode 100644 example/config/initializers/inflections.rb create mode 100644 example/config/initializers/mime_types.rb create mode 100644 example/config/initializers/passwd.rb create mode 100644 example/config/initializers/session_store.rb create mode 100644 example/config/initializers/wrap_parameters.rb create mode 100644 example/config/locales/en.yml create mode 100644 example/config/routes.rb create mode 100644 example/config/secrets.yml create mode 100644 example/db/seeds.rb create mode 100644 example/lib/assets/.keep create mode 100644 example/lib/tasks/.keep create mode 100644 example/log/.keep create mode 100644 example/public/404.html create mode 100644 example/public/422.html create mode 100644 example/public/500.html create mode 100644 example/public/favicon.ico create mode 100644 example/public/robots.txt create mode 100644 example/vendor/assets/javascripts/.keep create mode 100644 example/vendor/assets/stylesheets/.keep create mode 100644 spec/passwd/active_record_ext_spec.rb diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..6a502e9 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,16 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-journal + +# Ignore all logfiles and tempfiles. +/log/*.log +/tmp diff --git a/example/Gemfile b/example/Gemfile new file mode 100644 index 0000000..c310dc9 --- /dev/null +++ b/example/Gemfile @@ -0,0 +1,21 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '4.1.8' +# Use sqlite3 as the database for Active Record +gem 'sqlite3' +# Use SCSS for stylesheets +gem 'sass-rails', '~> 4.0.3' +# Use Uglifier as compressor for JavaScript assets +gem 'uglifier', '>= 1.3.0' +# Use CoffeeScript for .js.coffee assets and views +gem 'coffee-rails', '~> 4.0.0' + +# Use jquery as the JavaScript library +gem 'jquery-rails' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' + +gem 'passwd', path: File.expand_path("../..", __FILE__) + diff --git a/example/README.rdoc b/example/README.rdoc new file mode 100644 index 0000000..dd4e97e --- /dev/null +++ b/example/README.rdoc @@ -0,0 +1,28 @@ +== README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... + + +Please feel free to use a different markup language if you do not plan to run +rake doc:app. diff --git a/example/Rakefile b/example/Rakefile new file mode 100644 index 0000000..ba6b733 --- /dev/null +++ b/example/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require File.expand_path('../config/application', __FILE__) + +Rails.application.load_tasks diff --git a/example/app/assets/images/.keep b/example/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/assets/javascripts/application.js b/example/app/assets/javascripts/application.js new file mode 100644 index 0000000..d6925fa --- /dev/null +++ b/example/app/assets/javascripts/application.js @@ -0,0 +1,16 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, +// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// compiled file. +// +// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details +// about supported directives. +// +//= require jquery +//= require jquery_ujs +//= require turbolinks +//= require_tree . diff --git a/example/app/assets/stylesheets/application.css b/example/app/assets/stylesheets/application.css new file mode 100644 index 0000000..a443db3 --- /dev/null +++ b/example/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any styles + * defined in the other CSS/SCSS files in this directory. It is generally better to create a new + * file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/example/app/controllers/application_controller.rb b/example/app/controllers/application_controller.rb new file mode 100644 index 0000000..d83690e --- /dev/null +++ b/example/app/controllers/application_controller.rb @@ -0,0 +1,5 @@ +class ApplicationController < ActionController::Base + # Prevent CSRF attacks by raising an exception. + # For APIs, you may want to use :null_session instead. + protect_from_forgery with: :exception +end diff --git a/example/app/controllers/concerns/.keep b/example/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/helpers/application_helper.rb b/example/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/example/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/example/app/mailers/.keep b/example/app/mailers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models/.keep b/example/app/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models/concerns/.keep b/example/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/views/layouts/application.html.erb b/example/app/views/layouts/application.html.erb new file mode 100644 index 0000000..356e2e7 --- /dev/null +++ b/example/app/views/layouts/application.html.erb @@ -0,0 +1,14 @@ + + + + Example + <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> + <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> + <%= csrf_meta_tags %> + + + +<%= yield %> + + + diff --git a/example/bin/bundle b/example/bin/bundle new file mode 100755 index 0000000..66e9889 --- /dev/null +++ b/example/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/example/bin/rails b/example/bin/rails new file mode 100755 index 0000000..728cd85 --- /dev/null +++ b/example/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../../config/application', __FILE__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/example/bin/rake b/example/bin/rake new file mode 100755 index 0000000..1724048 --- /dev/null +++ b/example/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/example/config.ru b/example/config.ru new file mode 100644 index 0000000..5bc2a61 --- /dev/null +++ b/example/config.ru @@ -0,0 +1,4 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) +run Rails.application diff --git a/example/config/application.rb b/example/config/application.rb new file mode 100644 index 0000000..ee6bc29 --- /dev/null +++ b/example/config/application.rb @@ -0,0 +1,30 @@ +require File.expand_path('../boot', __FILE__) + +# Pick the frameworks you want: +require "active_model/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "sprockets/railtie" +# require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Example + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. + # config.time_zone = 'Central Time (US & Canada)' + + # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] + # config.i18n.default_locale = :de + end +end diff --git a/example/config/boot.rb b/example/config/boot.rb new file mode 100644 index 0000000..5e5f0c1 --- /dev/null +++ b/example/config/boot.rb @@ -0,0 +1,4 @@ +# Set up gems listed in the Gemfile. +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) + +require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/example/config/database.yml b/example/config/database.yml new file mode 100644 index 0000000..84f572e --- /dev/null +++ b/example/config/database.yml @@ -0,0 +1,26 @@ +# SQLite version 3.x +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' +# +default: &default + adapter: sqlite3 + pool: 5 + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: ":memory:" + +production: + <<: *default + database: db/production.sqlite3 + diff --git a/example/config/environment.rb b/example/config/environment.rb new file mode 100644 index 0000000..ee8d90d --- /dev/null +++ b/example/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require File.expand_path('../application', __FILE__) + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/example/config/environments/development.rb b/example/config/environments/development.rb new file mode 100644 index 0000000..ddf0e90 --- /dev/null +++ b/example/config/environments/development.rb @@ -0,0 +1,37 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Adds additional error checking when serving assets at runtime. + # Checks for improperly declared sprockets dependencies. + # Raises helpful error messages. + config.assets.raise_runtime_errors = true + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/example/config/environments/production.rb b/example/config/environments/production.rb new file mode 100644 index 0000000..b93a877 --- /dev/null +++ b/example/config/environments/production.rb @@ -0,0 +1,78 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Enable Rack::Cache to put a simple HTTP cache in front of your application + # Add `rack-cache` to your Gemfile before enabling this. + # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. + # config.action_dispatch.rack_cache = true + + # Disable Rails's static asset server (Apache or nginx will already do this). + config.serve_static_assets = false + + # Compress JavaScripts and CSS. + config.assets.js_compressor = :uglifier + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Generate digests for assets URLs. + config.assets.digest = true + + # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Set to :debug to see everything in the log. + config.log_level = :info + + # Prepend all log lines with the following tags. + # config.log_tags = [ :subdomain, :uuid ] + + # Use a different logger for distributed setups. + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = "http://assets.example.com" + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Disable automatic flushing of the log to improve performance. + # config.autoflush_log = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/example/config/environments/test.rb b/example/config/environments/test.rb new file mode 100644 index 0000000..053f5b6 --- /dev/null +++ b/example/config/environments/test.rb @@ -0,0 +1,39 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure static asset server for tests with Cache-Control for performance. + config.serve_static_assets = true + config.static_cache_control = 'public, max-age=3600' + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/example/config/initializers/assets.rb b/example/config/initializers/assets.rb new file mode 100644 index 0000000..d2f4ec3 --- /dev/null +++ b/example/config/initializers/assets.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in app/assets folder are already added. +# Rails.application.config.assets.precompile += %w( search.js ) diff --git a/example/config/initializers/backtrace_silencers.rb b/example/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..59385cd --- /dev/null +++ b/example/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/example/config/initializers/cookies_serializer.rb b/example/config/initializers/cookies_serializer.rb new file mode 100644 index 0000000..7a06a89 --- /dev/null +++ b/example/config/initializers/cookies_serializer.rb @@ -0,0 +1,3 @@ +# Be sure to restart your server when you modify this file. + +Rails.application.config.action_dispatch.cookies_serializer = :json \ No newline at end of file diff --git a/example/config/initializers/filter_parameter_logging.rb b/example/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..4a994e1 --- /dev/null +++ b/example/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/example/config/initializers/inflections.rb b/example/config/initializers/inflections.rb new file mode 100644 index 0000000..ac033bf --- /dev/null +++ b/example/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/example/config/initializers/mime_types.rb b/example/config/initializers/mime_types.rb new file mode 100644 index 0000000..dc18996 --- /dev/null +++ b/example/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/example/config/initializers/passwd.rb b/example/config/initializers/passwd.rb new file mode 100644 index 0000000..160dfc0 --- /dev/null +++ b/example/config/initializers/passwd.rb @@ -0,0 +1,41 @@ +Passwd.configure do |c| + # Password settings + # The following settings are all default values. + + # Hashing algorithm + # Supported algorithm is :md5, :rmd160, :sha1, :sha256, :sha384 and :sha512 + # c.algorithm = :sha512 + + # Random generate password length + # c.length = 8 + + # Number of hashed by stretching + # Not stretching if specified nil. + # c.stretching = nil + + # Character type that is used for password + # c.lower = true + # c.upper = true + # c.number = true +end + +Passwd.policy_configure do |c| + # Minimum password length + # c.min_length = 8 + + # Character types to force the use + # c.require_lower = true + # c.require_upper = false + # c.require_number = true +end + +# Session key for authentication +Rails.application.config.passwd.session_key = :user_id + +# Authentication Model Class +Rails.application.config.passwd.authenticate_class = :User + +# Redirect path when not signin +# E.G. :signin_path # Do not specify ***_url +Rails.application.config.passwd.redirect_to = nil + diff --git a/example/config/initializers/session_store.rb b/example/config/initializers/session_store.rb new file mode 100644 index 0000000..a9d774e --- /dev/null +++ b/example/config/initializers/session_store.rb @@ -0,0 +1,3 @@ +# Be sure to restart your server when you modify this file. + +Rails.application.config.session_store :cookie_store, key: '_example_session' diff --git a/example/config/initializers/wrap_parameters.rb b/example/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000..33725e9 --- /dev/null +++ b/example/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] if respond_to?(:wrap_parameters) +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/example/config/locales/en.yml b/example/config/locales/en.yml new file mode 100644 index 0000000..0653957 --- /dev/null +++ b/example/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/example/config/routes.rb b/example/config/routes.rb new file mode 100644 index 0000000..3f66539 --- /dev/null +++ b/example/config/routes.rb @@ -0,0 +1,56 @@ +Rails.application.routes.draw do + # The priority is based upon order of creation: first created -> highest priority. + # See how all your routes lay out with "rake routes". + + # You can have the root of your site routed with "root" + # root 'welcome#index' + + # Example of regular route: + # get 'products/:id' => 'catalog#view' + + # Example of named route that can be invoked with purchase_url(id: product.id) + # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase + + # Example resource route (maps HTTP verbs to controller actions automatically): + # resources :products + + # Example resource route with options: + # resources :products do + # member do + # get 'short' + # post 'toggle' + # end + # + # collection do + # get 'sold' + # end + # end + + # Example resource route with sub-resources: + # resources :products do + # resources :comments, :sales + # resource :seller + # end + + # Example resource route with more complex sub-resources: + # resources :products do + # resources :comments + # resources :sales do + # get 'recent', on: :collection + # end + # end + + # Example resource route with concerns: + # concern :toggleable do + # post 'toggle' + # end + # resources :posts, concerns: :toggleable + # resources :photos, concerns: :toggleable + + # Example resource route within a namespace: + # namespace :admin do + # # Directs /admin/products/* to Admin::ProductsController + # # (app/controllers/admin/products_controller.rb) + # resources :products + # end +end diff --git a/example/config/secrets.yml b/example/config/secrets.yml new file mode 100644 index 0000000..43a9c00 --- /dev/null +++ b/example/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rake secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: a38276b6c841e220a18cfc6f82463c9f7e6fa24093d7a8d525a7c5870c7f4eb082fe62e149153e8b5e1e43fd7b512f01715107ff3e557484301967c536699841 + +test: + secret_key_base: f9fa283d957fae581da09a284674f9ad4a720c8c93dbc662058d60b1b52e5c32ac3d6db5d9022c462311716f7eee002b6cf24dd0b29000aad673f15798364905 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/example/db/seeds.rb b/example/db/seeds.rb new file mode 100644 index 0000000..4edb1e8 --- /dev/null +++ b/example/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). +# +# Examples: +# +# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) +# Mayor.create(name: 'Emanuel', city: cities.first) diff --git a/example/lib/assets/.keep b/example/lib/assets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/lib/tasks/.keep b/example/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/log/.keep b/example/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/public/404.html b/example/public/404.html new file mode 100644 index 0000000..b612547 --- /dev/null +++ b/example/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +

+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/422.html b/example/public/422.html new file mode 100644 index 0000000..a21f82b --- /dev/null +++ b/example/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/500.html b/example/public/500.html new file mode 100644 index 0000000..061abc5 --- /dev/null +++ b/example/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/favicon.ico b/example/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/example/public/robots.txt b/example/public/robots.txt new file mode 100644 index 0000000..3c9c7c0 --- /dev/null +++ b/example/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/example/vendor/assets/javascripts/.keep b/example/vendor/assets/javascripts/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/vendor/assets/stylesheets/.keep b/example/vendor/assets/stylesheets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/passwd.gemspec b/passwd.gemspec index 9a845a8..01dff2d 100644 --- a/passwd.gemspec +++ b/passwd.gemspec @@ -19,8 +19,10 @@ Gem::Specification.new do |spec| spec.add_development_dependency "bundler" spec.add_development_dependency "rake" - spec.add_development_dependency "rspec" spec.add_development_dependency "coveralls" spec.add_development_dependency "simplecov" + spec.add_development_dependency "rails" + spec.add_development_dependency "rspec-rails" + spec.add_development_dependency "sqlite3" end diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb new file mode 100644 index 0000000..c195451 --- /dev/null +++ b/spec/passwd/active_record_ext_spec.rb @@ -0,0 +1,8 @@ +require "spec_helper" + +describe Passwd::ActiveRecordExt do + context ".#with_authenticate" do + it {expect(ActiveRecord::Base.respond_to? :with_authenticate).to be_truthy} + end +end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index a1a3049..522c8b5 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -10,8 +10,11 @@ SimpleCov.start do add_filter "spec" add_filter ".bundle" + add_filter "example" end +ENV["RAILS_ENV"] ||= "test" +require File.expand_path("../../example/config/environment", __FILE__) require "passwd" RSpec.configure do |config| From bf87b53eacafcba2ce5a320fa7c883298334fd1c Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sun, 23 Nov 2014 01:29:00 +0900 Subject: [PATCH 10/14] add specs and bug fix --- lib/passwd.rb | 5 +-- lib/passwd/base.rb | 10 ++--- lib/passwd/configuration.rb | 16 ++++--- lib/passwd/password.rb | 6 +-- spec/passwd/active_record_ext_spec.rb | 2 +- spec/passwd/base_spec.rb | 64 +++++++++++++++++++++++++++ spec/passwd/configuration_spec.rb | 46 +++++++++++++++++++ spec/spec_helper.rb | 1 + 8 files changed, 133 insertions(+), 17 deletions(-) create mode 100644 spec/passwd/base_spec.rb create mode 100644 spec/passwd/configuration_spec.rb diff --git a/lib/passwd.rb b/lib/passwd.rb index 996e0db..3cbc52c 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -8,12 +8,11 @@ require "passwd/base" require "passwd/salt" require "passwd/password" -require "passwd/railtie" +require "passwd/railtie" if defined?(Rails) module Passwd - include Configuration::Accessible - extend Configuration::Writable extend Base + extend Configuration::Writable def self.policy_check(plain) Password.from_plain(plain).valid? diff --git a/lib/passwd/base.rb b/lib/passwd/base.rb index 82e7be5..686ba9f 100644 --- a/lib/passwd/base.rb +++ b/lib/passwd/base.rb @@ -1,16 +1,16 @@ module Passwd module Base def random(options = {}) - c = Config.merge(options) + c = PwConfig.merge(options) Array.new(c.length){c.letters[rand(c.letters.size)]}.join end def digest(plain, _algorithm = nil) - _algorithm ||= Config.algorithm + _algorithm ||= PwConfig.algorithm - if Config.stretching + if PwConfig.stretching _pass = plain - Config.stretching.times do + PwConfig.stretching.times do _pass = digest_without_stretching(_pass, _algorithm) end else @@ -19,7 +19,7 @@ def digest(plain, _algorithm = nil) end def digest_without_stretching(plain, _algorithm = nil) - algorithm(_algorithm || Config.algorithm).hexdigest(plain) + algorithm(_algorithm || PwConfig.algorithm).hexdigest(plain) end private diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb index f84c4b4..151c511 100644 --- a/lib/passwd/configuration.rb +++ b/lib/passwd/configuration.rb @@ -39,7 +39,9 @@ def merge!(params) def letters KINDS.detect {|k| self.send(k)} || (raise ConfigError, "letters is empry.") - LETTERS.map {|l| self.send(l)}.flatten + LETTERS.zip(KINDS).map {|l, k| + self.send(l) if self.send(k) + }.compact.flatten end def reset @@ -56,19 +58,23 @@ def reset end module Writable + def self.extended(base) + base.include(Accessible) unless defined?(base::PwConfig) + end + def configure(options = {}, &block) - Config.merge!(options) unless options.empty? - Config.configure(&block) if block_given? + PwConfig.merge!(options) unless options.empty? + PwConfig.configure(&block) if block_given? end def policy_configure(&block) - Config.policy.configure(&block) if block_given? + PwConfig.policy.configure(&block) if block_given? end end module Accessible def self.included(base) - base.const_set(:Config, Configuration.new) + base.const_set(:PwConfig, Configuration.new) end end end diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index 6fe296e..db53258 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -56,11 +56,11 @@ def to_s def valid? raise PasswdError unless self.plain - return false if Config.policy.min_length > self.plain.size + return false if PwConfig.policy.min_length > self.plain.size Configuration::KINDS.each do |key| - if Config.policy.send("require_#{key}") - return false unless include_char?(Config.send("letters_#{key}")) + if PwConfig.policy.send("require_#{key}") + return false unless include_char?(PwConfig.send("letters_#{key}")) end end true diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb index c195451..fe43f67 100644 --- a/spec/passwd/active_record_ext_spec.rb +++ b/spec/passwd/active_record_ext_spec.rb @@ -2,7 +2,7 @@ describe Passwd::ActiveRecordExt do context ".#with_authenticate" do - it {expect(ActiveRecord::Base.respond_to? :with_authenticate).to be_truthy} + it { expect(ActiveRecord::Base.respond_to? :with_authenticate).to be_truthy } end end diff --git a/spec/passwd/base_spec.rb b/spec/passwd/base_spec.rb new file mode 100644 index 0000000..b9f6f24 --- /dev/null +++ b/spec/passwd/base_spec.rb @@ -0,0 +1,64 @@ +require "spec_helper" + +describe Passwd::Base do + let(:included) { Class.new {include Passwd::Base}.new } + let(:extended) { Class.new {extend Passwd::Base} } + let(:plain) { "secret" } + + context "#random" do + it { expect(included.respond_to?(:random)).to be_truthy } + it { expect(extended.respond_to?(:random)).to be_truthy } + it { expect(included.random.is_a?(String)).to be_truthy } + it { expect(included.random.size).to eq(Passwd::PwConfig.length) } + it { expect(("a".."z").to_a.include? Passwd.random(lower: false)).to be_falsey } + it { expect(("A".."Z").to_a.include? Passwd.random(upper: false)).to be_falsey } + it { expect(("0".."9").to_a.include? Passwd.random(number: false)).to be_falsey } + + it { + length = Passwd::PwConfig.length + 1 + expect(included.random(length: length).size).to eq(length) + } + + it { + lower = ["a"] + expect( + included.random(letters_lower: lower, upper: false, number: false) + .chars.uniq + ).to eq(lower) + } + end + + context "#digest" do + it { expect(included.respond_to?(:digest)).to be_truthy } + it { expect(extended.respond_to?(:digest)).to be_truthy } + it { expect(included.digest(plain).is_a?(String)).to be_truthy } + it { expect(included.digest(plain)).not_to eq(plain) } + + it { + hashed = included.send(:algorithm, Passwd::PwConfig.algorithm).hexdigest plain + expect(Passwd.digest(plain)).to eq(hashed) + } + + it { + not_default = :md5 + hashed = included.send(:algorithm, not_default).hexdigest plain + expect(Passwd.digest(plain, not_default)).to eq(hashed) + } + end + + context "#algorithm" do + it { expect(included.send(:algorithm, :sha1)).to eq(Digest::SHA1) } + it { expect(included.send(:algorithm, :sha256)).to eq(Digest::SHA256) } + it { expect(included.send(:algorithm, :sha384)).to eq(Digest::SHA384) } + it { expect(included.send(:algorithm, :sha512)).to eq(Digest::SHA512) } + it { expect(included.send(:algorithm, :md5)).to eq(Digest::MD5) } + it { expect(included.send(:algorithm, :rmd160)).to eq(Digest::RMD160) } + + it { + expect { + included.send(:algorithm, :unknowAn) + }.to raise_error + } + end +end + diff --git a/spec/passwd/configuration_spec.rb b/spec/passwd/configuration_spec.rb new file mode 100644 index 0000000..d5351ea --- /dev/null +++ b/spec/passwd/configuration_spec.rb @@ -0,0 +1,46 @@ +require "spec_helper" + +describe Passwd::Configuration do + describe "#initialize" do + subject(:config) { Passwd::PwConfig } + # defined options + it { expect(config.respond_to? :algorithm).to be_truthy } + it { expect(config.respond_to? :length).to be_truthy } + it { expect(config.respond_to? :policy).to be_truthy } + it { expect(config.respond_to? :stretching).to be_truthy } + it { expect(config.respond_to? :lower).to be_truthy } + it { expect(config.respond_to? :upper).to be_truthy } + it { expect(config.respond_to? :number).to be_truthy } + it { expect(config.respond_to? :letters_lower).to be_truthy } + it { expect(config.respond_to? :letters_upper).to be_truthy } + it { expect(config.respond_to? :letters_number).to be_truthy } + + # default settings + it { expect(config.algorithm).to eq(:sha512) } + it { expect(config.length).to eq(8) } + it { expect(config.policy.is_a?(Passwd::Policy)).to be_truthy } + it { expect(config.stretching).to eq(nil) } + it { expect(config.lower).to be_truthy } + it { expect(config.upper).to be_truthy } + it { expect(config.number).to be_truthy } + it { expect(config.letters_lower).to eq(("a".."z").to_a) } + it { expect(config.letters_upper).to eq(("A".."Z").to_a) } + it { expect(config.letters_number).to eq(("0".."9").to_a) } + end + + describe "Writable" do + it { + passwd = Class.new {extend Passwd::Configuration::Writable} + expect(defined?(passwd::PwConfig)).to be_truthy + } + + it { expect(Passwd.respond_to?(:configure)).to be_truthy } + it { expect(Passwd.respond_to?(:policy_configure)).to be_truthy } + end + + describe "Accessible" do + let(:passwd) { Class.new {include Passwd::Configuration::Accessible} } + it { expect(passwd::PwConfig.is_a?(Passwd::Configuration)).to be_truthy } + end +end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 522c8b5..169ee94 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -19,5 +19,6 @@ RSpec.configure do |config| config.order = "random" + config.after { Passwd::PwConfig.reset } end From d474c3df7f94bf196b7e681bce9413cf0671465c Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sun, 23 Nov 2014 02:40:52 +0900 Subject: [PATCH 11/14] add user model to example --- example/app/models/user.rb | 4 +++ .../db/migrate/20141122165914_create_users.rb | 13 ++++++++++ example/db/schema.rb | 25 +++++++++++++++++++ spec/passwd/active_record_ext_spec.rb | 8 ++++++ spec/spec_helper.rb | 3 +++ spec/support/paths.rb | 2 ++ 6 files changed, 55 insertions(+) create mode 100644 example/app/models/user.rb create mode 100644 example/db/migrate/20141122165914_create_users.rb create mode 100644 example/db/schema.rb create mode 100644 spec/support/paths.rb diff --git a/example/app/models/user.rb b/example/app/models/user.rb new file mode 100644 index 0000000..564499a --- /dev/null +++ b/example/app/models/user.rb @@ -0,0 +1,4 @@ +class User < ActiveRecord::Base + with_authenticate +end + diff --git a/example/db/migrate/20141122165914_create_users.rb b/example/db/migrate/20141122165914_create_users.rb new file mode 100644 index 0000000..3793187 --- /dev/null +++ b/example/db/migrate/20141122165914_create_users.rb @@ -0,0 +1,13 @@ +class CreateUsers < ActiveRecord::Migration + def change + create_table :users do |t| + t.string :name + t.string :email + t.string :salt + t.string :password + + t.timestamps + end + end +end + diff --git a/example/db/schema.rb b/example/db/schema.rb new file mode 100644 index 0000000..5a5371b --- /dev/null +++ b/example/db/schema.rb @@ -0,0 +1,25 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 20141122165914) do + + create_table "users", force: true do |t| + t.string "name" + t.string "email" + t.string "salt" + t.string "password" + t.datetime "created_at" + t.datetime "updated_at" + end + +end diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb index fe43f67..e6efda1 100644 --- a/spec/passwd/active_record_ext_spec.rb +++ b/spec/passwd/active_record_ext_spec.rb @@ -4,5 +4,13 @@ context ".#with_authenticate" do it { expect(ActiveRecord::Base.respond_to? :with_authenticate).to be_truthy } end + + describe User do + it { is_expected.to respond_to(:passwd) } + it { is_expected.to respond_to(:authenticate) } + it { expect(User).to respond_to(:authenticate) } + it { is_expected.to respond_to(:set_password) } + it { is_expected.to respond_to(:update_password) } + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 169ee94..b83283b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -17,8 +17,11 @@ require File.expand_path("../../example/config/environment", __FILE__) require "passwd" +Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} + RSpec.configure do |config| config.order = "random" + config.before(:all) { require "db/schema" } config.after { Passwd::PwConfig.reset } end diff --git a/spec/support/paths.rb b/spec/support/paths.rb new file mode 100644 index 0000000..9d0b730 --- /dev/null +++ b/spec/support/paths.rb @@ -0,0 +1,2 @@ +$:.unshift(Rails.root.to_s) unless $:.include?(Rails.root.to_s) + From 8e5e09cb8e33bb3c9aae6dca0b783541a22b32a4 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sun, 23 Nov 2014 04:25:08 +0900 Subject: [PATCH 12/14] fix specs and bug fix --- lib/passwd/password.rb | 8 +-- lib/passwd/salt.rb | 6 +-- spec/passwd/active_record_ext_spec.rb | 18 +++---- spec/passwd/base_spec.rb | 44 ++++++++-------- spec/passwd/configuration_spec.rb | 58 +++++++++++---------- spec/passwd/password_spec.rb | 74 +++++++++++++++++++++++++++ 6 files changed, 141 insertions(+), 67 deletions(-) create mode 100644 spec/passwd/password_spec.rb diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index db53258..befe046 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -21,19 +21,19 @@ def initialize(options = {}) else Salt.new(password: self) end - self.plain = options[:plain] + self.update_plain(options[:plain]) end end - def plain=(value) + def update_plain(value) @plain = value rehash end - def hash=(value, salt_hash) + def update_hash(value, salt_hash) @plain = nil @hash = value - self.salt.hash = salt_hash + self.salt.update_hash(salt_hash) end def rehash diff --git a/lib/passwd/salt.rb b/lib/passwd/salt.rb index 2c3c5a0..aa9b886 100644 --- a/lib/passwd/salt.rb +++ b/lib/passwd/salt.rb @@ -17,13 +17,13 @@ def initialize(options = {}) end end - def plain=(value) + def update_plain(value) @plain = value @hash = digest_without_stretching(@plain) update_password! end - def hash=(value) + def update_hash(value) @plain = nil @hash = value update_password! @@ -43,7 +43,7 @@ def default_options end def update_password! - @password.rehash if @password + @password.rehash if @password && @password.plain end end end diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb index e6efda1..10ae5b2 100644 --- a/spec/passwd/active_record_ext_spec.rb +++ b/spec/passwd/active_record_ext_spec.rb @@ -1,16 +1,16 @@ require "spec_helper" describe Passwd::ActiveRecordExt do - context ".#with_authenticate" do - it { expect(ActiveRecord::Base.respond_to? :with_authenticate).to be_truthy } - end + context ".with_authenticate" do + it { expect(ActiveRecord::Base).to respond_to(:with_authenticate) } - describe User do - it { is_expected.to respond_to(:passwd) } - it { is_expected.to respond_to(:authenticate) } - it { expect(User).to respond_to(:authenticate) } - it { is_expected.to respond_to(:set_password) } - it { is_expected.to respond_to(:update_password) } + context User do + it { is_expected.to respond_to(:passwd) } + it { is_expected.to respond_to(:authenticate) } + it { expect(User).to respond_to(:authenticate) } + it { is_expected.to respond_to(:set_password) } + it { is_expected.to respond_to(:update_password) } + end end end diff --git a/spec/passwd/base_spec.rb b/spec/passwd/base_spec.rb index b9f6f24..30b7694 100644 --- a/spec/passwd/base_spec.rb +++ b/spec/passwd/base_spec.rb @@ -1,62 +1,58 @@ require "spec_helper" describe Passwd::Base do - let(:included) { Class.new {include Passwd::Base}.new } - let(:extended) { Class.new {extend Passwd::Base} } let(:plain) { "secret" } context "#random" do - it { expect(included.respond_to?(:random)).to be_truthy } - it { expect(extended.respond_to?(:random)).to be_truthy } - it { expect(included.random.is_a?(String)).to be_truthy } - it { expect(included.random.size).to eq(Passwd::PwConfig.length) } - it { expect(("a".."z").to_a.include? Passwd.random(lower: false)).to be_falsey } - it { expect(("A".."Z").to_a.include? Passwd.random(upper: false)).to be_falsey } - it { expect(("0".."9").to_a.include? Passwd.random(number: false)).to be_falsey } + it { expect(Passwd).to respond_to(:random) } + it { expect(Passwd.random.is_a?(String)).to be_truthy } + it { expect(Passwd.random.size).to eq(Passwd::PwConfig.length) } + it { expect(Passwd.random(lower: false)).not_to include(*"a".."z") } + it { expect(Passwd.random(upper: false)).not_to include(*"A".."Z") } + it { expect(Passwd.random(number: false)).not_to include(*"0".."9") } it { length = Passwd::PwConfig.length + 1 - expect(included.random(length: length).size).to eq(length) + expect(Passwd.random(length: length).size).to eq(length) } it { lower = ["a"] expect( - included.random(letters_lower: lower, upper: false, number: false) + Passwd.random(letters_lower: lower, upper: false, number: false) .chars.uniq ).to eq(lower) } end context "#digest" do - it { expect(included.respond_to?(:digest)).to be_truthy } - it { expect(extended.respond_to?(:digest)).to be_truthy } - it { expect(included.digest(plain).is_a?(String)).to be_truthy } - it { expect(included.digest(plain)).not_to eq(plain) } + it { expect(Passwd.respond_to?(:digest)).to be_truthy } + it { expect(Passwd.digest(plain).is_a?(String)).to be_truthy } + it { expect(Passwd.digest(plain)).not_to eq(plain) } it { - hashed = included.send(:algorithm, Passwd::PwConfig.algorithm).hexdigest plain + hashed = Passwd.send(:algorithm, Passwd::PwConfig.algorithm).hexdigest plain expect(Passwd.digest(plain)).to eq(hashed) } it { not_default = :md5 - hashed = included.send(:algorithm, not_default).hexdigest plain + hashed = Passwd.send(:algorithm, not_default).hexdigest plain expect(Passwd.digest(plain, not_default)).to eq(hashed) } end context "#algorithm" do - it { expect(included.send(:algorithm, :sha1)).to eq(Digest::SHA1) } - it { expect(included.send(:algorithm, :sha256)).to eq(Digest::SHA256) } - it { expect(included.send(:algorithm, :sha384)).to eq(Digest::SHA384) } - it { expect(included.send(:algorithm, :sha512)).to eq(Digest::SHA512) } - it { expect(included.send(:algorithm, :md5)).to eq(Digest::MD5) } - it { expect(included.send(:algorithm, :rmd160)).to eq(Digest::RMD160) } + it { expect(Passwd.send(:algorithm, :sha1)).to eq(Digest::SHA1) } + it { expect(Passwd.send(:algorithm, :sha256)).to eq(Digest::SHA256) } + it { expect(Passwd.send(:algorithm, :sha384)).to eq(Digest::SHA384) } + it { expect(Passwd.send(:algorithm, :sha512)).to eq(Digest::SHA512) } + it { expect(Passwd.send(:algorithm, :md5)).to eq(Digest::MD5) } + it { expect(Passwd.send(:algorithm, :rmd160)).to eq(Digest::RMD160) } it { expect { - included.send(:algorithm, :unknowAn) + Passwd.send(:algorithm, :unknowAn) }.to raise_error } end diff --git a/spec/passwd/configuration_spec.rb b/spec/passwd/configuration_spec.rb index d5351ea..cca2dc4 100644 --- a/spec/passwd/configuration_spec.rb +++ b/spec/passwd/configuration_spec.rb @@ -2,45 +2,49 @@ describe Passwd::Configuration do describe "#initialize" do - subject(:config) { Passwd::PwConfig } + subject { Passwd::PwConfig } # defined options - it { expect(config.respond_to? :algorithm).to be_truthy } - it { expect(config.respond_to? :length).to be_truthy } - it { expect(config.respond_to? :policy).to be_truthy } - it { expect(config.respond_to? :stretching).to be_truthy } - it { expect(config.respond_to? :lower).to be_truthy } - it { expect(config.respond_to? :upper).to be_truthy } - it { expect(config.respond_to? :number).to be_truthy } - it { expect(config.respond_to? :letters_lower).to be_truthy } - it { expect(config.respond_to? :letters_upper).to be_truthy } - it { expect(config.respond_to? :letters_number).to be_truthy } + it { is_expected.to respond_to(:algorithm) } + it { is_expected.to respond_to(:length) } + it { is_expected.to respond_to(:policy) } + it { is_expected.to respond_to(:stretching) } + it { is_expected.to respond_to(:lower) } + it { is_expected.to respond_to(:upper) } + it { is_expected.to respond_to(:number) } + it { is_expected.to respond_to(:letters_lower) } + it { is_expected.to respond_to(:letters_upper) } + it { is_expected.to respond_to(:letters_number) } # default settings - it { expect(config.algorithm).to eq(:sha512) } - it { expect(config.length).to eq(8) } - it { expect(config.policy.is_a?(Passwd::Policy)).to be_truthy } - it { expect(config.stretching).to eq(nil) } - it { expect(config.lower).to be_truthy } - it { expect(config.upper).to be_truthy } - it { expect(config.number).to be_truthy } - it { expect(config.letters_lower).to eq(("a".."z").to_a) } - it { expect(config.letters_upper).to eq(("A".."Z").to_a) } - it { expect(config.letters_number).to eq(("0".."9").to_a) } + it { is_expected.to have_attributes(algorithm: :sha512) } + it { is_expected.to have_attributes(length: 8) } + it { is_expected.to satisfy {|v| v.policy.is_a?(Passwd::Policy) } } + it { is_expected.to have_attributes(stretching: nil) } + it { is_expected.to have_attributes(lower: true) } + it { is_expected.to have_attributes(upper: true) } + it { is_expected.to have_attributes(number: true) } + it { is_expected.to have_attributes(letters_lower: [*"a".."z"]) } + it { is_expected.to have_attributes(letters_upper: [*"A".."Z"]) } + it { is_expected.to have_attributes(letters_number: [*"0".."9"]) } end describe "Writable" do + subject { Passwd } + it { - passwd = Class.new {extend Passwd::Configuration::Writable} - expect(defined?(passwd::PwConfig)).to be_truthy + klass = Class.new { extend Passwd::Configuration::Writable } + expect(defined?(klass::PwConfig)).to be_truthy } - it { expect(Passwd.respond_to?(:configure)).to be_truthy } - it { expect(Passwd.respond_to?(:policy_configure)).to be_truthy } + it { is_expected.to respond_to(:configure) } + it { is_expected.to respond_to(:policy_configure) } end describe "Accessible" do - let(:passwd) { Class.new {include Passwd::Configuration::Accessible} } - it { expect(passwd::PwConfig.is_a?(Passwd::Configuration)).to be_truthy } + it { + klass = Class.new { include Passwd::Configuration::Accessible } + expect(klass::PwConfig.is_a?(Passwd::Configuration)).to be_truthy + } end end diff --git a/spec/passwd/password_spec.rb b/spec/passwd/password_spec.rb new file mode 100644 index 0000000..2f33e23 --- /dev/null +++ b/spec/passwd/password_spec.rb @@ -0,0 +1,74 @@ +require "spec_helper" + +describe Passwd::Password do + let!(:pswd) { Passwd::Password.new } + + describe "#initialize" do + context "without argument" do + subject { Passwd::Password.new } + + it { is_expected.not_to have_attributes(plain: nil) } + it { is_expected.not_to have_attributes(hash: nil) } + it { is_expected.not_to have_attributes(salt: nil) } + it { is_expected.to satisfy {|v| v.salt.is_a?(Passwd::Salt) } } + end + + context "with plain" do + subject { Passwd::Password.new(plain: pswd.plain) } + + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.not_to have_attributes(hash: nil) } + it { is_expected.not_to have_attributes(salt: nil) } + it { is_expected.to satisfy {|v| v.salt.is_a?(Passwd::Salt) } } + end + + context "with plain and salt_plain" do + subject { Passwd::Password.new(plain: pswd.plain, salt_plain: pswd.salt.plain) } + + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain == pswd.salt.plain } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } + end + + context "with plain and salt_hash" do + subject { Passwd::Password.new(plain: pswd.plain, salt_hash: pswd.salt.hash) } + + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain.nil? } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } + end + + context "with hash and salt_hash" do + subject { Passwd::Password.new(hash: pswd.hash, salt_hash: pswd.salt.hash) } + + it { is_expected.to have_attributes(plain: nil) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain.nil? } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } + end + + it { + expect { + Passwd::Password.new(hash: pswd.hash) + }.to raise_error(ArgumentError) + } + end + + describe "#update_plain" do + it { + expect(pswd).to receive(:rehash) + pswd.update_plain("secret") + expect(pswd).to have_attributes(plain: "secret") + } + end + + describe "#update_hash" do + it { + expect { + pswd.update_hash("hashed", "salt") + }.to change { pswd.plain } + } + end +end From 7a86ceb6bc4c7d400dc7b0bf5346d1b567240da4 Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sun, 23 Nov 2014 05:45:11 +0900 Subject: [PATCH 13/14] fix specs and bug fix --- lib/passwd/active_record_ext.rb | 2 +- lib/passwd/configuration.rb | 2 +- passwd.gemspec | 1 + spec/passwd/active_record_ext_spec.rb | 66 ++++++++++++++++++++- spec/passwd/password_spec.rb | 82 +++++++++++++++++++++++++++ spec/spec_helper.rb | 11 +++- spec/support/data_util.rb | 11 ++++ 7 files changed, 170 insertions(+), 5 deletions(-) create mode 100644 spec/support/data_util.rb diff --git a/lib/passwd/active_record_ext.rb b/lib/passwd/active_record_ext.rb index 79fa8fc..8c4e0d9 100644 --- a/lib/passwd/active_record_ext.rb +++ b/lib/passwd/active_record_ext.rb @@ -16,7 +16,7 @@ def with_authenticate(options = {}) def _define_passwd(_salt_key, _pass_key) define_method :passwd do |cache = true| return @_passwd if cache && @_passwd - self.reload + self.reload unless self.new_record? _salt, _pass = self.send(_salt_key), self.send(_pass_key) if _salt.present? && _pass.present? @_passwd = Passwd::Password.from_hash(_pass, _salt) diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb index 151c511..d745050 100644 --- a/lib/passwd/configuration.rb +++ b/lib/passwd/configuration.rb @@ -59,7 +59,7 @@ def reset module Writable def self.extended(base) - base.include(Accessible) unless defined?(base::PwConfig) + base.send(:include, Accessible) end def configure(options = {}, &block) diff --git a/passwd.gemspec b/passwd.gemspec index 01dff2d..5d23f21 100644 --- a/passwd.gemspec +++ b/passwd.gemspec @@ -24,5 +24,6 @@ Gem::Specification.new do |spec| spec.add_development_dependency "rails" spec.add_development_dependency "rspec-rails" spec.add_development_dependency "sqlite3" + spec.add_development_dependency "database_rewinder" end diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb index 10ae5b2..78a0be0 100644 --- a/spec/passwd/active_record_ext_spec.rb +++ b/spec/passwd/active_record_ext_spec.rb @@ -1,15 +1,79 @@ require "spec_helper" describe Passwd::ActiveRecordExt do - context ".with_authenticate" do + describe ".with_authenticate" do it { expect(ActiveRecord::Base).to respond_to(:with_authenticate) } context User do + let(:new_pass) { "NewPassw0rd" } + let(:password) { Passwd::Password.new } + let(:user) { + User.create( + name: "i2bskn", + email: "i2bskn@example.com", + salt: password.salt.hash, + password: password.hash + ) + } + it { is_expected.to respond_to(:passwd) } it { is_expected.to respond_to(:authenticate) } it { expect(User).to respond_to(:authenticate) } it { is_expected.to respond_to(:set_password) } it { is_expected.to respond_to(:update_password) } + + context "#passwd" do + after { user.passwd } + + it { expect(user.passwd.is_a?(Passwd::Password)).to be_truthy } + it { expect(user).to receive(:reload) } + it { expect(Passwd::Password).to receive(:from_hash) } + + it { + user = User.new + expect(user).to receive(:set_password) + user.passwd + } + end + + context ".authenticate" do + before { user } + + it { expect(User.authenticate("i2bskn@example.com", password.plain)).not_to be_falsy } + it { expect(User.authenticate("i2bskn@example.com", "invalid")).to be_falsy } + end + + context "#authenticate" do + it { expect(user.authenticate(password.plain)).not_to be_falsy } + it { expect(user.authenticate("invalid")).to be_falsy } + end + + context "#set_password" do + it { expect { user.set_password }.to change { user.password } } + it { expect { user.set_password(new_pass) }.to change { user.password } } + end + + context "#update_password" do + before { user } + + it { + expect { + user.update_password(password.plain, new_pass) + }.to change { user.password } + } + + it { + expect { + user.update_password(password.plain, "secret", true) + }.to raise_error(Passwd::PolicyNotMatch) + } + + it { + expect { + user.update_password("invalid", new_pass) + }.to raise_error(Passwd::AuthenticationFails) + } + end end end end diff --git a/spec/passwd/password_spec.rb b/spec/passwd/password_spec.rb index 2f33e23..1b88ff7 100644 --- a/spec/passwd/password_spec.rb +++ b/spec/passwd/password_spec.rb @@ -62,13 +62,95 @@ pswd.update_plain("secret") expect(pswd).to have_attributes(plain: "secret") } + + it { + expect { + pswd.update_plain("secret") + }.to change { pswd.plain } + } end describe "#update_hash" do + it { + expect(pswd).not_to receive(:rehash) + pswd.update_hash("hashed", "salt") + expect(pswd).to have_attributes(hash: "hashed") + expect(pswd.salt).to have_attributes(hash: "salt") + } + it { expect { pswd.update_hash("hashed", "salt") }.to change { pswd.plain } } end + + describe "#match?" do + it { expect(pswd.match?(pswd.plain)).to be_truthy } + + it { + invalid = [pswd.plain, "invalid"].join + expect(pswd.match?(invalid)).to be_falsy + } + end + + describe "#==" do + it { + expect(pswd).to receive(:match?) + pswd == pswd.plain + } + end + + describe "#valid?" do + it { + pswd.update_plain("ValidPassw0rd") + expect(pswd.valid?).to be_truthy + } + + it { + pswd.update_plain("a" * (Passwd::PwConfig.policy.min_length - 1)) + expect(pswd.valid?).to be_falsy + } + + it { + pswd.update_hash("hashed", "salt") + expect { + pswd.valid? + }.to raise_error(Passwd::PasswdError) + } + end + + describe "#default_options" do + it { + expect(pswd.send(:default_options)).to satisfy {|v| v.has_key?(:plain) } + } + end + + describe "#include_char?" do + it { + pswd.update_plain("secret") + expect(pswd.send(:include_char?, ["s"])).to be_truthy + } + + it { + expect { + pswd.update_hash("hashed", "salt") + pswd.send(:include_char?, []) + }.to raise_error(Passwd::PasswdError) + } + end + + describe ".from_plain" do + it { + expect(Passwd::Password).to receive(:new) + Passwd::Password.from_plain("secret") + } + end + + describe ".from_hash" do + it { + expect(Passwd::Password).to receive(:new) + Passwd::Password.from_hash("hashed", "salt") + } + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b83283b..627da67 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -21,7 +21,14 @@ RSpec.configure do |config| config.order = "random" - config.before(:all) { require "db/schema" } - config.after { Passwd::PwConfig.reset } + + config.before :all do + require "db/schema" + end + + config.after :each do + Passwd::PwConfig.reset + DataUtil.clear + end end diff --git a/spec/support/data_util.rb b/spec/support/data_util.rb new file mode 100644 index 0000000..3e195f7 --- /dev/null +++ b/spec/support/data_util.rb @@ -0,0 +1,11 @@ +class DataUtil + TARGETS = %w(User) + + def self.clear + models.each(&:delete_all) + end + + def self.models + TARGETS.map(&:constantize) + end +end From fdd4ccb713bf53afa079035503481845340cb5bc Mon Sep 17 00:00:00 2001 From: i2bskn Date: Sun, 23 Nov 2014 06:52:25 +0900 Subject: [PATCH 14/14] add signin function to example app --- README.md | 1 + example/Gemfile | 4 ++ example/app/assets/javascripts/application.js | 2 +- .../app/assets/stylesheets/application.css | 1 + .../app/controllers/application_controller.rb | 5 ++ example/app/controllers/root_controller.rb | 5 ++ .../app/controllers/sessions_controller.rb | 29 +++++++++ .../app/views/layouts/application.html.erb | 5 +- example/app/views/root/index.html.erb | 4 ++ example/app/views/sessions/new.html.erb | 6 ++ example/config/application.rb | 10 +++ example/config/initializers/passwd.rb | 2 +- example/config/routes.rb | 64 +++---------------- example/lib/tasks/user.rake | 12 ++++ 14 files changed, 92 insertions(+), 58 deletions(-) create mode 100644 example/app/controllers/root_controller.rb create mode 100644 example/app/controllers/sessions_controller.rb create mode 100644 example/app/views/root/index.html.erb create mode 100644 example/app/views/sessions/new.html.erb create mode 100644 example/lib/tasks/user.rake diff --git a/README.md b/README.md index 43a0102..4138747 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ class SessionsController < ApplicationController def destroy # Clear session (Only user_id) signout! + redirect_to some_url end end ``` diff --git a/example/Gemfile b/example/Gemfile index c310dc9..9471824 100644 --- a/example/Gemfile +++ b/example/Gemfile @@ -19,3 +19,7 @@ gem 'jbuilder', '~> 2.0' gem 'passwd', path: File.expand_path("../..", __FILE__) +group :development do + gem 'pry-rails' +end + diff --git a/example/app/assets/javascripts/application.js b/example/app/assets/javascripts/application.js index d6925fa..06353a5 100644 --- a/example/app/assets/javascripts/application.js +++ b/example/app/assets/javascripts/application.js @@ -12,5 +12,5 @@ // //= require jquery //= require jquery_ujs -//= require turbolinks //= require_tree . + diff --git a/example/app/assets/stylesheets/application.css b/example/app/assets/stylesheets/application.css index a443db3..9499f25 100644 --- a/example/app/assets/stylesheets/application.css +++ b/example/app/assets/stylesheets/application.css @@ -13,3 +13,4 @@ *= require_tree . *= require_self */ + diff --git a/example/app/controllers/application_controller.rb b/example/app/controllers/application_controller.rb index d83690e..1283d1a 100644 --- a/example/app/controllers/application_controller.rb +++ b/example/app/controllers/application_controller.rb @@ -2,4 +2,9 @@ class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception + + # Require authentication all access! + # Specified `skil_before_action` if not authenticate + before_action :require_signin end + diff --git a/example/app/controllers/root_controller.rb b/example/app/controllers/root_controller.rb new file mode 100644 index 0000000..7881449 --- /dev/null +++ b/example/app/controllers/root_controller.rb @@ -0,0 +1,5 @@ +class RootController < ApplicationController + # GET / + def index; end +end + diff --git a/example/app/controllers/sessions_controller.rb b/example/app/controllers/sessions_controller.rb new file mode 100644 index 0000000..e9477cc --- /dev/null +++ b/example/app/controllers/sessions_controller.rb @@ -0,0 +1,29 @@ +class SessionsController < ApplicationController + # If you has been enabled `require_signin` in ApplicationController + skip_before_action :require_signin + + # GET /signin + def new; end + + # POST /signin + def create + # Returns nil or user + @user = User.authenticate(params[:email], params[:password]) + + if @user + # Save user_id to session + signin!(@user) + redirect_to root_url + else # Authentication fails + render action: :new + end + end + + # DELETE /signout + def destroy + # Clear session (Only user_id) + signout! + redirect_to signin_url + end +end + diff --git a/example/app/views/layouts/application.html.erb b/example/app/views/layouts/application.html.erb index 356e2e7..017c550 100644 --- a/example/app/views/layouts/application.html.erb +++ b/example/app/views/layouts/application.html.erb @@ -2,8 +2,8 @@ Example - <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> - <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> + <%= stylesheet_link_tag 'application', media: 'all' %> + <%= javascript_include_tag 'application' %> <%= csrf_meta_tags %> @@ -12,3 +12,4 @@ + diff --git a/example/app/views/root/index.html.erb b/example/app/views/root/index.html.erb new file mode 100644 index 0000000..ebc17a1 --- /dev/null +++ b/example/app/views/root/index.html.erb @@ -0,0 +1,4 @@ +

Hello <%= current_user.name %>!!

+ +<%= link_to "Signout!", signout_path, method: :delete, data: { confirm: "Are you sure?" } %> + diff --git a/example/app/views/sessions/new.html.erb b/example/app/views/sessions/new.html.erb new file mode 100644 index 0000000..d16a2cf --- /dev/null +++ b/example/app/views/sessions/new.html.erb @@ -0,0 +1,6 @@ +<%= form_tag create_session_path do %> + <%= email_field_tag :email, @email, placeholder: "E-Mail", required: true %> + <%= password_field_tag :password, nil, placeholder: "Password", required: true %> + <%= submit_tag "Signin" %> +<% end %> + diff --git a/example/config/application.rb b/example/config/application.rb index ee6bc29..4159ee9 100644 --- a/example/config/application.rb +++ b/example/config/application.rb @@ -22,9 +22,19 @@ class Application < Rails::Application # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' + config.time_zone = "Tokyo" + config.active_record.default_timezone = :local # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de + I18n.enforce_available_locales = false + config.i18n.default_locale = :ja + + config.generators do |g| + g.stylesheets false + g.javascripts false + g.helper false + end end end diff --git a/example/config/initializers/passwd.rb b/example/config/initializers/passwd.rb index 160dfc0..3951fe1 100644 --- a/example/config/initializers/passwd.rb +++ b/example/config/initializers/passwd.rb @@ -37,5 +37,5 @@ # Redirect path when not signin # E.G. :signin_path # Do not specify ***_url -Rails.application.config.passwd.redirect_to = nil +Rails.application.config.passwd.redirect_to = :signin_path diff --git a/example/config/routes.rb b/example/config/routes.rb index 3f66539..a1181dc 100644 --- a/example/config/routes.rb +++ b/example/config/routes.rb @@ -1,56 +1,12 @@ Rails.application.routes.draw do - # The priority is based upon order of creation: first created -> highest priority. - # See how all your routes lay out with "rake routes". - - # You can have the root of your site routed with "root" - # root 'welcome#index' - - # Example of regular route: - # get 'products/:id' => 'catalog#view' - - # Example of named route that can be invoked with purchase_url(id: product.id) - # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase - - # Example resource route (maps HTTP verbs to controller actions automatically): - # resources :products - - # Example resource route with options: - # resources :products do - # member do - # get 'short' - # post 'toggle' - # end - # - # collection do - # get 'sold' - # end - # end - - # Example resource route with sub-resources: - # resources :products do - # resources :comments, :sales - # resource :seller - # end - - # Example resource route with more complex sub-resources: - # resources :products do - # resources :comments - # resources :sales do - # get 'recent', on: :collection - # end - # end - - # Example resource route with concerns: - # concern :toggleable do - # post 'toggle' - # end - # resources :posts, concerns: :toggleable - # resources :photos, concerns: :toggleable - - # Example resource route within a namespace: - # namespace :admin do - # # Directs /admin/products/* to Admin::ProductsController - # # (app/controllers/admin/products_controller.rb) - # resources :products - # end + controller :sessions do + get :signin, to: :new, as: :signin + post :signin, to: :create, as: :create_session + delete :signout, to: :destroy, as: :signout + end + + controller :root do + root to: :index + end end + diff --git a/example/lib/tasks/user.rake b/example/lib/tasks/user.rake new file mode 100644 index 0000000..b39846d --- /dev/null +++ b/example/lib/tasks/user.rake @@ -0,0 +1,12 @@ +namespace :user do + desc "User create for development" + task :create => :environment do + User.find_or_create_by(email: "develop@example.com") do |u| + u.name = "developer" + u.salt = "fdb4bb5a745232d43874088c8edfcbaf5975d0d1e254016015991f1f3c4fc7061fd2f379b7d1f40504ddd1ff2f5feeb2caa0df895af5cb036b39f53f5ca79b04" + # password => "secret" + u.password = "636641d912523d7868614deed094797bfa3e9d504e0e01ab76ee2c7246555b41ff657169ac1ddbba9972fc324bc48c7fe479c0d2858105300ee203df6aeb53cc" + end + end +end +